babylon.no-module.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050
  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. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. */
  581. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  582. var _this = this;
  583. this._isReady = false;
  584. this._vertexSourceCodeOverride = vertexSourceCode;
  585. this._fragmentSourceCodeOverride = fragmentSourceCode;
  586. this.onError = function (effect, error) {
  587. if (onError) {
  588. onError(error);
  589. }
  590. };
  591. this.onCompiled = function () {
  592. var scenes = _this.getEngine().scenes;
  593. for (var i = 0; i < scenes.length; i++) {
  594. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  595. }
  596. if (onCompiled) {
  597. onCompiled(_this._program);
  598. }
  599. };
  600. this._fallbacks = null;
  601. this._prepareEffect();
  602. };
  603. /**
  604. * Gets the uniform locations of the the specified variable names
  605. * @param names THe names of the variables to lookup.
  606. * @returns Array of locations in the same order as variable names.
  607. */
  608. Effect.prototype.getSpecificUniformLocations = function (names) {
  609. var engine = this._engine;
  610. return engine.getUniforms(this._program, names);
  611. };
  612. /**
  613. * Prepares the effect
  614. */
  615. Effect.prototype._prepareEffect = function () {
  616. var attributesNames = this._attributesNames;
  617. var defines = this.defines;
  618. var fallbacks = this._fallbacks;
  619. this._valueCache = {};
  620. var previousProgram = this._program;
  621. try {
  622. var engine = this._engine;
  623. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  624. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  625. }
  626. else {
  627. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  628. }
  629. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  630. if (engine.supportsUniformBuffers) {
  631. for (var name in this._uniformBuffersNames) {
  632. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  633. }
  634. }
  635. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  636. this._attributes = engine.getAttributes(this._program, attributesNames);
  637. var index;
  638. for (index = 0; index < this._samplers.length; index++) {
  639. var sampler = this.getUniform(this._samplers[index]);
  640. if (sampler == null) {
  641. this._samplers.splice(index, 1);
  642. index--;
  643. }
  644. }
  645. engine.bindSamplers(this);
  646. this._compilationError = "";
  647. this._isReady = true;
  648. if (this.onCompiled) {
  649. this.onCompiled(this);
  650. }
  651. this.onCompileObservable.notifyObservers(this);
  652. this.onCompileObservable.clear();
  653. // Unbind mesh reference in fallbacks
  654. if (this._fallbacks) {
  655. this._fallbacks.unBindMesh();
  656. }
  657. if (previousProgram) {
  658. this.getEngine()._deleteProgram(previousProgram);
  659. }
  660. }
  661. catch (e) {
  662. this._compilationError = e.message;
  663. // Let's go through fallbacks then
  664. BABYLON.Tools.Error("Unable to compile effect:");
  665. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  666. return " " + uniform;
  667. }));
  668. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  669. return " " + attribute;
  670. }));
  671. BABYLON.Tools.Error("Error: " + this._compilationError);
  672. if (previousProgram) {
  673. this._program = previousProgram;
  674. this._isReady = true;
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. }
  680. if (fallbacks && fallbacks.isMoreFallbacks) {
  681. BABYLON.Tools.Error("Trying next fallback.");
  682. this.defines = fallbacks.reduce(this.defines, this);
  683. this._prepareEffect();
  684. }
  685. else { // Sorry we did everything we can
  686. if (this.onError) {
  687. this.onError(this, this._compilationError);
  688. }
  689. this.onErrorObservable.notifyObservers(this);
  690. this.onErrorObservable.clear();
  691. // Unbind mesh reference in fallbacks
  692. if (this._fallbacks) {
  693. this._fallbacks.unBindMesh();
  694. }
  695. }
  696. }
  697. };
  698. Object.defineProperty(Effect.prototype, "isSupported", {
  699. /**
  700. * Checks if the effect is supported. (Must be called after compilation)
  701. */
  702. get: function () {
  703. return this._compilationError === "";
  704. },
  705. enumerable: true,
  706. configurable: true
  707. });
  708. /**
  709. * Binds a texture to the engine to be used as output of the shader.
  710. * @param channel Name of the output variable.
  711. * @param texture Texture to bind.
  712. */
  713. Effect.prototype._bindTexture = function (channel, texture) {
  714. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  715. };
  716. /**
  717. * Sets a texture on the engine to be used in the shader.
  718. * @param channel Name of the sampler variable.
  719. * @param texture Texture to set.
  720. */
  721. Effect.prototype.setTexture = function (channel, texture) {
  722. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  723. };
  724. /**
  725. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  726. * @param channel Name of the sampler variable.
  727. * @param texture Texture to set.
  728. */
  729. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  730. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  731. };
  732. /**
  733. * Sets an array of textures on the engine to be used in the shader.
  734. * @param channel Name of the variable.
  735. * @param textures Textures to set.
  736. */
  737. Effect.prototype.setTextureArray = function (channel, textures) {
  738. if (this._samplers.indexOf(channel + "Ex") === -1) {
  739. var initialPos = this._samplers.indexOf(channel);
  740. for (var index = 1; index < textures.length; index++) {
  741. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  742. }
  743. }
  744. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  745. };
  746. /**
  747. * 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)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the input texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /**
  755. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  756. * 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)
  757. * @param channel Name of the sampler variable.
  758. * @param postProcess Post process to get the output texture from.
  759. */
  760. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  761. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  762. };
  763. /** @hidden */
  764. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  765. var cache = this._valueCache[uniformName];
  766. var flag = matrix.updateFlag;
  767. if (cache !== undefined && cache === flag) {
  768. return false;
  769. }
  770. this._valueCache[uniformName] = flag;
  771. return true;
  772. };
  773. /** @hidden */
  774. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  775. var cache = this._valueCache[uniformName];
  776. if (!cache) {
  777. cache = [x, y];
  778. this._valueCache[uniformName] = cache;
  779. return true;
  780. }
  781. var changed = false;
  782. if (cache[0] !== x) {
  783. cache[0] = x;
  784. changed = true;
  785. }
  786. if (cache[1] !== y) {
  787. cache[1] = y;
  788. changed = true;
  789. }
  790. return changed;
  791. };
  792. /** @hidden */
  793. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  794. var cache = this._valueCache[uniformName];
  795. if (!cache) {
  796. cache = [x, y, z];
  797. this._valueCache[uniformName] = cache;
  798. return true;
  799. }
  800. var changed = false;
  801. if (cache[0] !== x) {
  802. cache[0] = x;
  803. changed = true;
  804. }
  805. if (cache[1] !== y) {
  806. cache[1] = y;
  807. changed = true;
  808. }
  809. if (cache[2] !== z) {
  810. cache[2] = z;
  811. changed = true;
  812. }
  813. return changed;
  814. };
  815. /** @hidden */
  816. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  817. var cache = this._valueCache[uniformName];
  818. if (!cache) {
  819. cache = [x, y, z, w];
  820. this._valueCache[uniformName] = cache;
  821. return true;
  822. }
  823. var changed = false;
  824. if (cache[0] !== x) {
  825. cache[0] = x;
  826. changed = true;
  827. }
  828. if (cache[1] !== y) {
  829. cache[1] = y;
  830. changed = true;
  831. }
  832. if (cache[2] !== z) {
  833. cache[2] = z;
  834. changed = true;
  835. }
  836. if (cache[3] !== w) {
  837. cache[3] = w;
  838. changed = true;
  839. }
  840. return changed;
  841. };
  842. /**
  843. * Binds a buffer to a uniform.
  844. * @param buffer Buffer to bind.
  845. * @param name Name of the uniform variable to bind to.
  846. */
  847. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  848. var bufferName = this._uniformBuffersNames[name];
  849. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  850. return;
  851. }
  852. Effect._baseCache[bufferName] = buffer;
  853. this._engine.bindUniformBufferBase(buffer, bufferName);
  854. };
  855. /**
  856. * Binds block to a uniform.
  857. * @param blockName Name of the block to bind.
  858. * @param index Index to bind.
  859. */
  860. Effect.prototype.bindUniformBlock = function (blockName, index) {
  861. this._engine.bindUniformBlock(this._program, blockName, index);
  862. };
  863. /**
  864. * Sets an interger value on a uniform variable.
  865. * @param uniformName Name of the variable.
  866. * @param value Value to be set.
  867. * @returns this effect.
  868. */
  869. Effect.prototype.setInt = function (uniformName, value) {
  870. var cache = this._valueCache[uniformName];
  871. if (cache !== undefined && cache === value)
  872. return this;
  873. this._valueCache[uniformName] = value;
  874. this._engine.setInt(this.getUniform(uniformName), value);
  875. return this;
  876. };
  877. /**
  878. * Sets an int array on a uniform variable.
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * 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)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray2 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray2(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * 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)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray3 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray3(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * 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)
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setIntArray4 = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setIntArray4(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * Sets an float array on a uniform variable.
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * 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)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * 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)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * 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)
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * Sets an array on a uniform variable.
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * 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)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray2 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray2(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * 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)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray3 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray3(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * 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)
  1000. * @param uniformName Name of the variable.
  1001. * @param array array to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setArray4 = function (uniformName, array) {
  1005. this._valueCache[uniformName] = null;
  1006. this._engine.setArray4(this.getUniform(uniformName), array);
  1007. return this;
  1008. };
  1009. /**
  1010. * Sets matrices on a uniform variable.
  1011. * @param uniformName Name of the variable.
  1012. * @param matrices matrices to be set.
  1013. * @returns this effect.
  1014. */
  1015. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1016. if (!matrices) {
  1017. return this;
  1018. }
  1019. this._valueCache[uniformName] = null;
  1020. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1021. return this;
  1022. };
  1023. /**
  1024. * Sets matrix on a uniform variable.
  1025. * @param uniformName Name of the variable.
  1026. * @param matrix matrix to be set.
  1027. * @returns this effect.
  1028. */
  1029. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1030. if (this._cacheMatrix(uniformName, matrix)) {
  1031. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1032. }
  1033. return this;
  1034. };
  1035. /**
  1036. * 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)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1048. * @param uniformName Name of the variable.
  1049. * @param matrix matrix to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1053. this._valueCache[uniformName] = null;
  1054. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1055. return this;
  1056. };
  1057. /**
  1058. * Sets a float on a uniform variable.
  1059. * @param uniformName Name of the variable.
  1060. * @param value value to be set.
  1061. * @returns this effect.
  1062. */
  1063. Effect.prototype.setFloat = function (uniformName, value) {
  1064. var cache = this._valueCache[uniformName];
  1065. if (cache !== undefined && cache === value)
  1066. return this;
  1067. this._valueCache[uniformName] = value;
  1068. this._engine.setFloat(this.getUniform(uniformName), value);
  1069. return this;
  1070. };
  1071. /**
  1072. * Sets a boolean on a uniform variable.
  1073. * @param uniformName Name of the variable.
  1074. * @param bool value to be set.
  1075. * @returns this effect.
  1076. */
  1077. Effect.prototype.setBool = function (uniformName, bool) {
  1078. var cache = this._valueCache[uniformName];
  1079. if (cache !== undefined && cache === bool)
  1080. return this;
  1081. this._valueCache[uniformName] = bool;
  1082. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a Vector2 on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param vector2 vector2 to be set.
  1089. * @returns this effect.
  1090. */
  1091. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1092. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1093. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1094. }
  1095. return this;
  1096. };
  1097. /**
  1098. * Sets a float2 on a uniform variable.
  1099. * @param uniformName Name of the variable.
  1100. * @param x First float in float2.
  1101. * @param y Second float in float2.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1105. if (this._cacheFloat2(uniformName, x, y)) {
  1106. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a Vector3 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param vector3 Value to be set.
  1114. * @returns this effect.
  1115. */
  1116. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1117. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1118. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1119. }
  1120. return this;
  1121. };
  1122. /**
  1123. * Sets a float3 on a uniform variable.
  1124. * @param uniformName Name of the variable.
  1125. * @param x First float in float3.
  1126. * @param y Second float in float3.
  1127. * @param z Third float in float3.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1131. if (this._cacheFloat3(uniformName, x, y, z)) {
  1132. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1133. }
  1134. return this;
  1135. };
  1136. /**
  1137. * Sets a Vector4 on a uniform variable.
  1138. * @param uniformName Name of the variable.
  1139. * @param vector4 Value to be set.
  1140. * @returns this effect.
  1141. */
  1142. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1143. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1144. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Sets a float4 on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param x First float in float4.
  1152. * @param y Second float in float4.
  1153. * @param z Third float in float4.
  1154. * @param w Fourth float in float4.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1158. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1159. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Color3 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param color3 Value to be set.
  1167. * @returns this effect.
  1168. */
  1169. Effect.prototype.setColor3 = function (uniformName, color3) {
  1170. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1171. this._engine.setColor3(this.getUniform(uniformName), color3);
  1172. }
  1173. return this;
  1174. };
  1175. /**
  1176. * Sets a Color4 on a uniform variable.
  1177. * @param uniformName Name of the variable.
  1178. * @param color3 Value to be set.
  1179. * @param alpha Alpha value to be set.
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1183. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1184. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Sets a Color4 on a uniform variable
  1190. * @param uniformName defines the name of the variable
  1191. * @param color4 defines the value to be set
  1192. * @returns this effect.
  1193. */
  1194. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1195. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1196. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1197. }
  1198. return this;
  1199. };
  1200. /**
  1201. * This function will add a new shader to the shader store
  1202. * @param name the name of the shader
  1203. * @param pixelShader optional pixel shader content
  1204. * @param vertexShader optional vertex shader content
  1205. */
  1206. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1207. if (pixelShader) {
  1208. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1209. }
  1210. if (vertexShader) {
  1211. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1212. }
  1213. };
  1214. /**
  1215. * Resets the cache of effects.
  1216. */
  1217. Effect.ResetCache = function () {
  1218. Effect._baseCache = {};
  1219. };
  1220. Effect._uniqueIdSeed = 0;
  1221. Effect._baseCache = {};
  1222. /**
  1223. * Store of each shader (The can be looked up using effect.key)
  1224. */
  1225. Effect.ShadersStore = {};
  1226. /**
  1227. * Store of each included file for a shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.IncludesShadersStore = {};
  1230. return Effect;
  1231. }());
  1232. BABYLON.Effect = Effect;
  1233. })(BABYLON || (BABYLON = {}));
  1234. //# sourceMappingURL=babylon.effect.js.map
  1235. //# sourceMappingURL=babylon.types.js.map
  1236. var BABYLON;
  1237. (function (BABYLON) {
  1238. var KeyboardEventTypes = /** @class */ (function () {
  1239. function KeyboardEventTypes() {
  1240. }
  1241. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1242. get: function () {
  1243. return KeyboardEventTypes._KEYDOWN;
  1244. },
  1245. enumerable: true,
  1246. configurable: true
  1247. });
  1248. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1249. get: function () {
  1250. return KeyboardEventTypes._KEYUP;
  1251. },
  1252. enumerable: true,
  1253. configurable: true
  1254. });
  1255. KeyboardEventTypes._KEYDOWN = 0x01;
  1256. KeyboardEventTypes._KEYUP = 0x02;
  1257. return KeyboardEventTypes;
  1258. }());
  1259. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1260. var KeyboardInfo = /** @class */ (function () {
  1261. function KeyboardInfo(type, event) {
  1262. this.type = type;
  1263. this.event = event;
  1264. }
  1265. return KeyboardInfo;
  1266. }());
  1267. BABYLON.KeyboardInfo = KeyboardInfo;
  1268. /**
  1269. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1270. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1271. */
  1272. var KeyboardInfoPre = /** @class */ (function (_super) {
  1273. __extends(KeyboardInfoPre, _super);
  1274. function KeyboardInfoPre(type, event) {
  1275. var _this = _super.call(this, type, event) || this;
  1276. _this.skipOnPointerObservable = false;
  1277. return _this;
  1278. }
  1279. return KeyboardInfoPre;
  1280. }(KeyboardInfo));
  1281. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1282. })(BABYLON || (BABYLON = {}));
  1283. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1284. var BABYLON;
  1285. (function (BABYLON) {
  1286. var PointerEventTypes = /** @class */ (function () {
  1287. function PointerEventTypes() {
  1288. }
  1289. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERDOWN;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1297. get: function () {
  1298. return PointerEventTypes._POINTERUP;
  1299. },
  1300. enumerable: true,
  1301. configurable: true
  1302. });
  1303. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1304. get: function () {
  1305. return PointerEventTypes._POINTERMOVE;
  1306. },
  1307. enumerable: true,
  1308. configurable: true
  1309. });
  1310. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1311. get: function () {
  1312. return PointerEventTypes._POINTERWHEEL;
  1313. },
  1314. enumerable: true,
  1315. configurable: true
  1316. });
  1317. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1318. get: function () {
  1319. return PointerEventTypes._POINTERPICK;
  1320. },
  1321. enumerable: true,
  1322. configurable: true
  1323. });
  1324. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1325. get: function () {
  1326. return PointerEventTypes._POINTERTAP;
  1327. },
  1328. enumerable: true,
  1329. configurable: true
  1330. });
  1331. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1332. get: function () {
  1333. return PointerEventTypes._POINTERDOUBLETAP;
  1334. },
  1335. enumerable: true,
  1336. configurable: true
  1337. });
  1338. PointerEventTypes._POINTERDOWN = 0x01;
  1339. PointerEventTypes._POINTERUP = 0x02;
  1340. PointerEventTypes._POINTERMOVE = 0x04;
  1341. PointerEventTypes._POINTERWHEEL = 0x08;
  1342. PointerEventTypes._POINTERPICK = 0x10;
  1343. PointerEventTypes._POINTERTAP = 0x20;
  1344. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1345. return PointerEventTypes;
  1346. }());
  1347. BABYLON.PointerEventTypes = PointerEventTypes;
  1348. var PointerInfoBase = /** @class */ (function () {
  1349. function PointerInfoBase(type, event) {
  1350. this.type = type;
  1351. this.event = event;
  1352. }
  1353. return PointerInfoBase;
  1354. }());
  1355. BABYLON.PointerInfoBase = PointerInfoBase;
  1356. /**
  1357. * This class is used to store pointer related info for the onPrePointerObservable event.
  1358. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1359. */
  1360. var PointerInfoPre = /** @class */ (function (_super) {
  1361. __extends(PointerInfoPre, _super);
  1362. function PointerInfoPre(type, event, localX, localY) {
  1363. var _this = _super.call(this, type, event) || this;
  1364. /**
  1365. * Ray from a pointer if availible (eg. 6dof controller)
  1366. */
  1367. _this.ray = null;
  1368. _this.skipOnPointerObservable = false;
  1369. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1370. return _this;
  1371. }
  1372. return PointerInfoPre;
  1373. }(PointerInfoBase));
  1374. BABYLON.PointerInfoPre = PointerInfoPre;
  1375. /**
  1376. * This type contains all the data related to a pointer event in Babylon.js.
  1377. * 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.
  1378. */
  1379. var PointerInfo = /** @class */ (function (_super) {
  1380. __extends(PointerInfo, _super);
  1381. function PointerInfo(type, event, pickInfo) {
  1382. var _this = _super.call(this, type, event) || this;
  1383. _this.pickInfo = pickInfo;
  1384. return _this;
  1385. }
  1386. return PointerInfo;
  1387. }(PointerInfoBase));
  1388. BABYLON.PointerInfo = PointerInfo;
  1389. })(BABYLON || (BABYLON = {}));
  1390. //# sourceMappingURL=babylon.pointerEvents.js.map
  1391. var BABYLON;
  1392. (function (BABYLON) {
  1393. BABYLON.ToGammaSpace = 1 / 2.2;
  1394. BABYLON.ToLinearSpace = 2.2;
  1395. BABYLON.Epsilon = 0.001;
  1396. /**
  1397. * Class used to hold a RBG color
  1398. */
  1399. var Color3 = /** @class */ (function () {
  1400. /**
  1401. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1402. * @param r defines the red component (between 0 and 1, default is 0)
  1403. * @param g defines the green component (between 0 and 1, default is 0)
  1404. * @param b defines the blue component (between 0 and 1, default is 0)
  1405. */
  1406. function Color3(
  1407. /**
  1408. * Defines the red component (between 0 and 1, default is 0)
  1409. */
  1410. r,
  1411. /**
  1412. * Defines the green component (between 0 and 1, default is 0)
  1413. */
  1414. g,
  1415. /**
  1416. * Defines the blue component (between 0 and 1, default is 0)
  1417. */
  1418. b) {
  1419. if (r === void 0) { r = 0; }
  1420. if (g === void 0) { g = 0; }
  1421. if (b === void 0) { b = 0; }
  1422. this.r = r;
  1423. this.g = g;
  1424. this.b = b;
  1425. }
  1426. /**
  1427. * Creates a string with the Color3 current values
  1428. * @returns the string representation of the Color3 object
  1429. */
  1430. Color3.prototype.toString = function () {
  1431. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1432. };
  1433. /**
  1434. * Returns the string "Color3"
  1435. * @returns "Color3"
  1436. */
  1437. Color3.prototype.getClassName = function () {
  1438. return "Color3";
  1439. };
  1440. /**
  1441. * Compute the Color3 hash code
  1442. * @returns an unique number that can be used to hash Color3 objects
  1443. */
  1444. Color3.prototype.getHashCode = function () {
  1445. var hash = this.r || 0;
  1446. hash = (hash * 397) ^ (this.g || 0);
  1447. hash = (hash * 397) ^ (this.b || 0);
  1448. return hash;
  1449. };
  1450. // Operators
  1451. /**
  1452. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1453. * @param array defines the array where to store the r,g,b components
  1454. * @param index defines an optional index in the target array to define where to start storing values
  1455. * @returns the current Color3 object
  1456. */
  1457. Color3.prototype.toArray = function (array, index) {
  1458. if (index === undefined) {
  1459. index = 0;
  1460. }
  1461. array[index] = this.r;
  1462. array[index + 1] = this.g;
  1463. array[index + 2] = this.b;
  1464. return this;
  1465. };
  1466. /**
  1467. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1468. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1469. * @returns a new {BABYLON.Color4} object
  1470. */
  1471. Color3.prototype.toColor4 = function (alpha) {
  1472. if (alpha === void 0) { alpha = 1; }
  1473. return new Color4(this.r, this.g, this.b, alpha);
  1474. };
  1475. /**
  1476. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1477. * @returns the new array
  1478. */
  1479. Color3.prototype.asArray = function () {
  1480. var result = new Array();
  1481. this.toArray(result, 0);
  1482. return result;
  1483. };
  1484. /**
  1485. * Returns the luminance value
  1486. * @returns a float value
  1487. */
  1488. Color3.prototype.toLuminance = function () {
  1489. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1490. };
  1491. /**
  1492. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1493. * @param otherColor defines the second operand
  1494. * @returns the new Color3 object
  1495. */
  1496. Color3.prototype.multiply = function (otherColor) {
  1497. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1498. };
  1499. /**
  1500. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1501. * @param otherColor defines the second operand
  1502. * @param result defines the Color3 object where to store the result
  1503. * @returns the current Color3
  1504. */
  1505. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1506. result.r = this.r * otherColor.r;
  1507. result.g = this.g * otherColor.g;
  1508. result.b = this.b * otherColor.b;
  1509. return this;
  1510. };
  1511. /**
  1512. * Determines equality between Color3 objects
  1513. * @param otherColor defines the second operand
  1514. * @returns true if the rgb values are equal to the given ones
  1515. */
  1516. Color3.prototype.equals = function (otherColor) {
  1517. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1518. };
  1519. /**
  1520. * Determines equality between the current Color3 object and a set of r,b,g values
  1521. * @param r defines the red component to check
  1522. * @param g defines the green component to check
  1523. * @param b defines the blue component to check
  1524. * @returns true if the rgb values are equal to the given ones
  1525. */
  1526. Color3.prototype.equalsFloats = function (r, g, b) {
  1527. return this.r === r && this.g === g && this.b === b;
  1528. };
  1529. /**
  1530. * Multiplies in place each rgb value by scale
  1531. * @param scale defines the scaling factor
  1532. * @returns the updated Color3
  1533. */
  1534. Color3.prototype.scale = function (scale) {
  1535. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1536. };
  1537. /**
  1538. * Multiplies the rgb values by scale and stores the result into "result"
  1539. * @param scale defines the scaling factor
  1540. * @param result defines the Color3 object where to store the result
  1541. * @returns the unmodified current Color3
  1542. */
  1543. Color3.prototype.scaleToRef = function (scale, result) {
  1544. result.r = this.r * scale;
  1545. result.g = this.g * scale;
  1546. result.b = this.b * scale;
  1547. return this;
  1548. };
  1549. /**
  1550. * Scale the current Color3 values by a factor and add the result to a given Color3
  1551. * @param scale defines the scale factor
  1552. * @param result defines color to store the result into
  1553. * @returns the unmodified current Color3
  1554. */
  1555. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1556. result.r += this.r * scale;
  1557. result.g += this.g * scale;
  1558. result.b += this.b * scale;
  1559. return this;
  1560. };
  1561. /**
  1562. * Clamps the rgb values by the min and max values and stores the result into "result"
  1563. * @param min defines minimum clamping value (default is 0)
  1564. * @param max defines maximum clamping value (default is 1)
  1565. * @param result defines color to store the result into
  1566. * @returns the original Color3
  1567. */
  1568. Color3.prototype.clampToRef = function (min, max, result) {
  1569. if (min === void 0) { min = 0; }
  1570. if (max === void 0) { max = 1; }
  1571. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1572. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1573. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1574. return this;
  1575. };
  1576. /**
  1577. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1578. * @param otherColor defines the second operand
  1579. * @returns the new Color3
  1580. */
  1581. Color3.prototype.add = function (otherColor) {
  1582. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1583. };
  1584. /**
  1585. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1586. * @param otherColor defines the second operand
  1587. * @param result defines Color3 object to store the result into
  1588. * @returns the unmodified current Color3
  1589. */
  1590. Color3.prototype.addToRef = function (otherColor, result) {
  1591. result.r = this.r + otherColor.r;
  1592. result.g = this.g + otherColor.g;
  1593. result.b = this.b + otherColor.b;
  1594. return this;
  1595. };
  1596. /**
  1597. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1598. * @param otherColor defines the second operand
  1599. * @returns the new Color3
  1600. */
  1601. Color3.prototype.subtract = function (otherColor) {
  1602. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1603. };
  1604. /**
  1605. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1606. * @param otherColor defines the second operand
  1607. * @param result defines Color3 object to store the result into
  1608. * @returns the unmodified current Color3
  1609. */
  1610. Color3.prototype.subtractToRef = function (otherColor, result) {
  1611. result.r = this.r - otherColor.r;
  1612. result.g = this.g - otherColor.g;
  1613. result.b = this.b - otherColor.b;
  1614. return this;
  1615. };
  1616. /**
  1617. * Copy the current object
  1618. * @returns a new Color3 copied the current one
  1619. */
  1620. Color3.prototype.clone = function () {
  1621. return new Color3(this.r, this.g, this.b);
  1622. };
  1623. /**
  1624. * Copies the rgb values from the source in the current Color3
  1625. * @param source defines the source Color3 object
  1626. * @returns the updated Color3 object
  1627. */
  1628. Color3.prototype.copyFrom = function (source) {
  1629. this.r = source.r;
  1630. this.g = source.g;
  1631. this.b = source.b;
  1632. return this;
  1633. };
  1634. /**
  1635. * Updates the Color3 rgb values from the given floats
  1636. * @param r defines the red component to read from
  1637. * @param g defines the green component to read from
  1638. * @param b defines the blue component to read from
  1639. * @returns the current Color3 object
  1640. */
  1641. Color3.prototype.copyFromFloats = function (r, g, b) {
  1642. this.r = r;
  1643. this.g = g;
  1644. this.b = b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Updates the Color3 rgb values from the given floats
  1649. * @param r defines the red component to read from
  1650. * @param g defines the green component to read from
  1651. * @param b defines the blue component to read from
  1652. * @returns the current Color3 object
  1653. */
  1654. Color3.prototype.set = function (r, g, b) {
  1655. return this.copyFromFloats(r, g, b);
  1656. };
  1657. /**
  1658. * Compute the Color3 hexadecimal code as a string
  1659. * @returns a string containing the hexadecimal representation of the Color3 object
  1660. */
  1661. Color3.prototype.toHexString = function () {
  1662. var intR = (this.r * 255) | 0;
  1663. var intG = (this.g * 255) | 0;
  1664. var intB = (this.b * 255) | 0;
  1665. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1666. };
  1667. /**
  1668. * Computes a new Color3 converted from the current one to linear space
  1669. * @returns a new Color3 object
  1670. */
  1671. Color3.prototype.toLinearSpace = function () {
  1672. var convertedColor = new Color3();
  1673. this.toLinearSpaceToRef(convertedColor);
  1674. return convertedColor;
  1675. };
  1676. /**
  1677. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1678. * @param convertedColor defines the Color3 object where to store the linear space version
  1679. * @returns the unmodified Color3
  1680. */
  1681. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1682. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1683. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1684. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1685. return this;
  1686. };
  1687. /**
  1688. * Computes a new Color3 converted from the current one to gamma space
  1689. * @returns a new Color3 object
  1690. */
  1691. Color3.prototype.toGammaSpace = function () {
  1692. var convertedColor = new Color3();
  1693. this.toGammaSpaceToRef(convertedColor);
  1694. return convertedColor;
  1695. };
  1696. /**
  1697. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1698. * @param convertedColor defines the Color3 object where to store the gamma space version
  1699. * @returns the unmodified Color3
  1700. */
  1701. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1702. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1703. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1704. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1705. return this;
  1706. };
  1707. // Statics
  1708. /**
  1709. * Creates a new Color3 from the string containing valid hexadecimal values
  1710. * @param hex defines a string containing valid hexadecimal values
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.FromHexString = function (hex) {
  1714. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1715. return new Color3(0, 0, 0);
  1716. }
  1717. var r = parseInt(hex.substring(1, 3), 16);
  1718. var g = parseInt(hex.substring(3, 5), 16);
  1719. var b = parseInt(hex.substring(5, 7), 16);
  1720. return Color3.FromInts(r, g, b);
  1721. };
  1722. /**
  1723. * Creates a new Vector3 from the starting index of the given array
  1724. * @param array defines the source array
  1725. * @param offset defines an offset in the source array
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.FromArray = function (array, offset) {
  1729. if (offset === void 0) { offset = 0; }
  1730. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1731. };
  1732. /**
  1733. * Creates a new Color3 from integer values (< 256)
  1734. * @param r defines the red component to read from (value between 0 and 255)
  1735. * @param g defines the green component to read from (value between 0 and 255)
  1736. * @param b defines the blue component to read from (value between 0 and 255)
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.FromInts = function (r, g, b) {
  1740. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1741. };
  1742. /**
  1743. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1744. * @param start defines the start Color3 value
  1745. * @param end defines the end Color3 value
  1746. * @param amount defines the gradient value between start and end
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Lerp = function (start, end, amount) {
  1750. var r = start.r + ((end.r - start.r) * amount);
  1751. var g = start.g + ((end.g - start.g) * amount);
  1752. var b = start.b + ((end.b - start.b) * amount);
  1753. return new Color3(r, g, b);
  1754. };
  1755. /**
  1756. * Returns a Color3 value containing a red color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Red = function () { return new Color3(1, 0, 0); };
  1760. /**
  1761. * Returns a Color3 value containing a green color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Green = function () { return new Color3(0, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a blue color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1770. /**
  1771. * Returns a Color3 value containing a black color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Black = function () { return new Color3(0, 0, 0); };
  1775. /**
  1776. * Returns a Color3 value containing a white color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.White = function () { return new Color3(1, 1, 1); };
  1780. /**
  1781. * Returns a Color3 value containing a purple color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1785. /**
  1786. * Returns a Color3 value containing a magenta color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1790. /**
  1791. * Returns a Color3 value containing a yellow color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a gray color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1800. /**
  1801. * Returns a Color3 value containing a teal color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1805. /**
  1806. * Returns a Color3 value containing a random color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1810. return Color3;
  1811. }());
  1812. BABYLON.Color3 = Color3;
  1813. /**
  1814. * Class used to hold a RBGA color
  1815. */
  1816. var Color4 = /** @class */ (function () {
  1817. /**
  1818. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1819. * @param r defines the red component (between 0 and 1, default is 0)
  1820. * @param g defines the green component (between 0 and 1, default is 0)
  1821. * @param b defines the blue component (between 0 and 1, default is 0)
  1822. * @param a defines the alpha component (between 0 and 1, default is 1)
  1823. */
  1824. function Color4(
  1825. /**
  1826. * Defines the red component (between 0 and 1, default is 0)
  1827. */
  1828. r,
  1829. /**
  1830. * Defines the green component (between 0 and 1, default is 0)
  1831. */
  1832. g,
  1833. /**
  1834. * Defines the blue component (between 0 and 1, default is 0)
  1835. */
  1836. b,
  1837. /**
  1838. * Defines the alpha component (between 0 and 1, default is 1)
  1839. */
  1840. a) {
  1841. if (r === void 0) { r = 0; }
  1842. if (g === void 0) { g = 0; }
  1843. if (b === void 0) { b = 0; }
  1844. if (a === void 0) { a = 1; }
  1845. this.r = r;
  1846. this.g = g;
  1847. this.b = b;
  1848. this.a = a;
  1849. }
  1850. // Operators
  1851. /**
  1852. * Adds in place the given Color4 values to the current Color4 object
  1853. * @param right defines the second operand
  1854. * @returns the current updated Color4 object
  1855. */
  1856. Color4.prototype.addInPlace = function (right) {
  1857. this.r += right.r;
  1858. this.g += right.g;
  1859. this.b += right.b;
  1860. this.a += right.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1865. * @returns the new array
  1866. */
  1867. Color4.prototype.asArray = function () {
  1868. var result = new Array();
  1869. this.toArray(result, 0);
  1870. return result;
  1871. };
  1872. /**
  1873. * Stores from the starting index in the given array the Color4 successive values
  1874. * @param array defines the array where to store the r,g,b components
  1875. * @param index defines an optional index in the target array to define where to start storing values
  1876. * @returns the current Color4 object
  1877. */
  1878. Color4.prototype.toArray = function (array, index) {
  1879. if (index === undefined) {
  1880. index = 0;
  1881. }
  1882. array[index] = this.r;
  1883. array[index + 1] = this.g;
  1884. array[index + 2] = this.b;
  1885. array[index + 3] = this.a;
  1886. return this;
  1887. };
  1888. /**
  1889. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1890. * @param right defines the second operand
  1891. * @returns a new Color4 object
  1892. */
  1893. Color4.prototype.add = function (right) {
  1894. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1895. };
  1896. /**
  1897. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1898. * @param right defines the second operand
  1899. * @returns a new Color4 object
  1900. */
  1901. Color4.prototype.subtract = function (right) {
  1902. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1903. };
  1904. /**
  1905. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1906. * @param right defines the second operand
  1907. * @param result defines the Color4 object where to store the result
  1908. * @returns the current Color4 object
  1909. */
  1910. Color4.prototype.subtractToRef = function (right, result) {
  1911. result.r = this.r - right.r;
  1912. result.g = this.g - right.g;
  1913. result.b = this.b - right.b;
  1914. result.a = this.a - right.a;
  1915. return this;
  1916. };
  1917. /**
  1918. * Creates a new Color4 with the current Color4 values multiplied by scale
  1919. * @param scale defines the scaling factor to apply
  1920. * @returns a new Color4 object
  1921. */
  1922. Color4.prototype.scale = function (scale) {
  1923. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1924. };
  1925. /**
  1926. * Multiplies the current Color4 values by scale and stores the result in "result"
  1927. * @param scale defines the scaling factor to apply
  1928. * @param result defines the Color4 object where to store the result
  1929. * @returns the current unmodified Color4
  1930. */
  1931. Color4.prototype.scaleToRef = function (scale, result) {
  1932. result.r = this.r * scale;
  1933. result.g = this.g * scale;
  1934. result.b = this.b * scale;
  1935. result.a = this.a * scale;
  1936. return this;
  1937. };
  1938. /**
  1939. * Scale the current Color4 values by a factor and add the result to a given Color4
  1940. * @param scale defines the scale factor
  1941. * @param result defines the Color4 object where to store the result
  1942. * @returns the unmodified current Color4
  1943. */
  1944. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1945. result.r += this.r * scale;
  1946. result.g += this.g * scale;
  1947. result.b += this.b * scale;
  1948. result.a += this.a * scale;
  1949. return this;
  1950. };
  1951. /**
  1952. * Clamps the rgb values by the min and max values and stores the result into "result"
  1953. * @param min defines minimum clamping value (default is 0)
  1954. * @param max defines maximum clamping value (default is 1)
  1955. * @param result defines color to store the result into.
  1956. * @returns the cuurent Color4
  1957. */
  1958. Color4.prototype.clampToRef = function (min, max, result) {
  1959. if (min === void 0) { min = 0; }
  1960. if (max === void 0) { max = 1; }
  1961. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1962. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1963. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1964. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1965. return this;
  1966. };
  1967. /**
  1968. * Multipy an Color4 value by another and return a new Color4 object
  1969. * @param color defines the Color4 value to multiply by
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.multiply = function (color) {
  1973. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1974. };
  1975. /**
  1976. * Multipy a Color4 value by another and push the result in a reference value
  1977. * @param color defines the Color4 value to multiply by
  1978. * @param result defines the Color4 to fill the result in
  1979. * @returns the result Color4
  1980. */
  1981. Color4.prototype.multiplyToRef = function (color, result) {
  1982. result.r = this.r * color.r;
  1983. result.g = this.g * color.g;
  1984. result.b = this.b * color.b;
  1985. result.a = this.a * color.a;
  1986. return result;
  1987. };
  1988. /**
  1989. * Creates a string with the Color4 current values
  1990. * @returns the string representation of the Color4 object
  1991. */
  1992. Color4.prototype.toString = function () {
  1993. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1994. };
  1995. /**
  1996. * Returns the string "Color4"
  1997. * @returns "Color4"
  1998. */
  1999. Color4.prototype.getClassName = function () {
  2000. return "Color4";
  2001. };
  2002. /**
  2003. * Compute the Color4 hash code
  2004. * @returns an unique number that can be used to hash Color4 objects
  2005. */
  2006. Color4.prototype.getHashCode = function () {
  2007. var hash = this.r || 0;
  2008. hash = (hash * 397) ^ (this.g || 0);
  2009. hash = (hash * 397) ^ (this.b || 0);
  2010. hash = (hash * 397) ^ (this.a || 0);
  2011. return hash;
  2012. };
  2013. /**
  2014. * Creates a new Color4 copied from the current one
  2015. * @returns a new Color4 object
  2016. */
  2017. Color4.prototype.clone = function () {
  2018. return new Color4(this.r, this.g, this.b, this.a);
  2019. };
  2020. /**
  2021. * Copies the given Color4 values into the current one
  2022. * @param source defines the source Color4 object
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.copyFrom = function (source) {
  2026. this.r = source.r;
  2027. this.g = source.g;
  2028. this.b = source.b;
  2029. this.a = source.a;
  2030. return this;
  2031. };
  2032. /**
  2033. * Copies the given float values into the current one
  2034. * @param r defines the red component to read from
  2035. * @param g defines the green component to read from
  2036. * @param b defines the blue component to read from
  2037. * @param a defines the alpha component to read from
  2038. * @returns the current updated Color4 object
  2039. */
  2040. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2041. this.r = r;
  2042. this.g = g;
  2043. this.b = b;
  2044. this.a = a;
  2045. return this;
  2046. };
  2047. /**
  2048. * Copies the given float values into the current one
  2049. * @param r defines the red component to read from
  2050. * @param g defines the green component to read from
  2051. * @param b defines the blue component to read from
  2052. * @param a defines the alpha component to read from
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.set = function (r, g, b, a) {
  2056. return this.copyFromFloats(r, g, b, a);
  2057. };
  2058. /**
  2059. * Compute the Color4 hexadecimal code as a string
  2060. * @returns a string containing the hexadecimal representation of the Color4 object
  2061. */
  2062. Color4.prototype.toHexString = function () {
  2063. var intR = (this.r * 255) | 0;
  2064. var intG = (this.g * 255) | 0;
  2065. var intB = (this.b * 255) | 0;
  2066. var intA = (this.a * 255) | 0;
  2067. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2068. };
  2069. /**
  2070. * Computes a new Color4 converted from the current one to linear space
  2071. * @returns a new Color4 object
  2072. */
  2073. Color4.prototype.toLinearSpace = function () {
  2074. var convertedColor = new Color4();
  2075. this.toLinearSpaceToRef(convertedColor);
  2076. return convertedColor;
  2077. };
  2078. /**
  2079. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2080. * @param convertedColor defines the Color4 object where to store the linear space version
  2081. * @returns the unmodified Color4
  2082. */
  2083. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2084. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2085. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2086. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2087. convertedColor.a = this.a;
  2088. return this;
  2089. };
  2090. /**
  2091. * Computes a new Color4 converted from the current one to gamma space
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.toGammaSpace = function () {
  2095. var convertedColor = new Color4();
  2096. this.toGammaSpaceToRef(convertedColor);
  2097. return convertedColor;
  2098. };
  2099. /**
  2100. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2101. * @param convertedColor defines the Color4 object where to store the gamma space version
  2102. * @returns the unmodified Color4
  2103. */
  2104. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2105. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2106. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2107. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2108. convertedColor.a = this.a;
  2109. return this;
  2110. };
  2111. // Statics
  2112. /**
  2113. * Creates a new Color4 from the string containing valid hexadecimal values
  2114. * @param hex defines a string containing valid hexadecimal values
  2115. * @returns a new Color4 object
  2116. */
  2117. Color4.FromHexString = function (hex) {
  2118. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2119. return new Color4(0.0, 0.0, 0.0, 0.0);
  2120. }
  2121. var r = parseInt(hex.substring(1, 3), 16);
  2122. var g = parseInt(hex.substring(3, 5), 16);
  2123. var b = parseInt(hex.substring(5, 7), 16);
  2124. var a = parseInt(hex.substring(7, 9), 16);
  2125. return Color4.FromInts(r, g, b, a);
  2126. };
  2127. /**
  2128. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2129. * @param left defines the start value
  2130. * @param right defines the end value
  2131. * @param amount defines the gradient factor
  2132. * @returns a new Color4 object
  2133. */
  2134. Color4.Lerp = function (left, right, amount) {
  2135. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2136. Color4.LerpToRef(left, right, amount, result);
  2137. return result;
  2138. };
  2139. /**
  2140. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2141. * @param left defines the start value
  2142. * @param right defines the end value
  2143. * @param amount defines the gradient factor
  2144. * @param result defines the Color4 object where to store data
  2145. */
  2146. Color4.LerpToRef = function (left, right, amount, result) {
  2147. result.r = left.r + (right.r - left.r) * amount;
  2148. result.g = left.g + (right.g - left.g) * amount;
  2149. result.b = left.b + (right.b - left.b) * amount;
  2150. result.a = left.a + (right.a - left.a) * amount;
  2151. };
  2152. /**
  2153. * Creates a new Color4 from the starting index element of the given array
  2154. * @param array defines the source array to read from
  2155. * @param offset defines the offset in the source array
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.FromArray = function (array, offset) {
  2159. if (offset === void 0) { offset = 0; }
  2160. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2161. };
  2162. /**
  2163. * Creates a new Color3 from integer values (< 256)
  2164. * @param r defines the red component to read from (value between 0 and 255)
  2165. * @param g defines the green component to read from (value between 0 and 255)
  2166. * @param b defines the blue component to read from (value between 0 and 255)
  2167. * @param a defines the alpha component to read from (value between 0 and 255)
  2168. * @returns a new Color3 object
  2169. */
  2170. Color4.FromInts = function (r, g, b, a) {
  2171. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2172. };
  2173. /**
  2174. * Check the content of a given array and convert it to an array containing RGBA data
  2175. * If the original array was already containing count * 4 values then it is returned directly
  2176. * @param colors defines the array to check
  2177. * @param count defines the number of RGBA data to expect
  2178. * @returns an array containing count * 4 values (RGBA)
  2179. */
  2180. Color4.CheckColors4 = function (colors, count) {
  2181. // Check if color3 was used
  2182. if (colors.length === count * 3) {
  2183. var colors4 = [];
  2184. for (var index = 0; index < colors.length; index += 3) {
  2185. var newIndex = (index / 3) * 4;
  2186. colors4[newIndex] = colors[index];
  2187. colors4[newIndex + 1] = colors[index + 1];
  2188. colors4[newIndex + 2] = colors[index + 2];
  2189. colors4[newIndex + 3] = 1.0;
  2190. }
  2191. return colors4;
  2192. }
  2193. return colors;
  2194. };
  2195. return Color4;
  2196. }());
  2197. BABYLON.Color4 = Color4;
  2198. /**
  2199. * Class representing a vector containing 2 coordinates
  2200. */
  2201. var Vector2 = /** @class */ (function () {
  2202. /**
  2203. * Creates a new Vector2 from the given x and y coordinates
  2204. * @param x defines the first coordinate
  2205. * @param y defines the second coordinate
  2206. */
  2207. function Vector2(
  2208. /** defines the first coordinate */
  2209. x,
  2210. /** defines the second coordinate */
  2211. y) {
  2212. if (x === void 0) { x = 0; }
  2213. if (y === void 0) { y = 0; }
  2214. this.x = x;
  2215. this.y = y;
  2216. }
  2217. /**
  2218. * Gets a string with the Vector2 coordinates
  2219. * @returns a string with the Vector2 coordinates
  2220. */
  2221. Vector2.prototype.toString = function () {
  2222. return "{X: " + this.x + " Y:" + this.y + "}";
  2223. };
  2224. /**
  2225. * Gets class name
  2226. * @returns the string "Vector2"
  2227. */
  2228. Vector2.prototype.getClassName = function () {
  2229. return "Vector2";
  2230. };
  2231. /**
  2232. * Gets current vector hash code
  2233. * @returns the Vector2 hash code as a number
  2234. */
  2235. Vector2.prototype.getHashCode = function () {
  2236. var hash = this.x || 0;
  2237. hash = (hash * 397) ^ (this.y || 0);
  2238. return hash;
  2239. };
  2240. // Operators
  2241. /**
  2242. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2243. * @param array defines the source array
  2244. * @param index defines the offset in source array
  2245. * @returns the current Vector2
  2246. */
  2247. Vector2.prototype.toArray = function (array, index) {
  2248. if (index === void 0) { index = 0; }
  2249. array[index] = this.x;
  2250. array[index + 1] = this.y;
  2251. return this;
  2252. };
  2253. /**
  2254. * Copy the current vector to an array
  2255. * @returns a new array with 2 elements: the Vector2 coordinates.
  2256. */
  2257. Vector2.prototype.asArray = function () {
  2258. var result = new Array();
  2259. this.toArray(result, 0);
  2260. return result;
  2261. };
  2262. /**
  2263. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2264. * @param source defines the source Vector2
  2265. * @returns the current updated Vector2
  2266. */
  2267. Vector2.prototype.copyFrom = function (source) {
  2268. this.x = source.x;
  2269. this.y = source.y;
  2270. return this;
  2271. };
  2272. /**
  2273. * Sets the Vector2 coordinates with the given floats
  2274. * @param x defines the first coordinate
  2275. * @param y defines the second coordinate
  2276. * @returns the current updated Vector2
  2277. */
  2278. Vector2.prototype.copyFromFloats = function (x, y) {
  2279. this.x = x;
  2280. this.y = y;
  2281. return this;
  2282. };
  2283. /**
  2284. * Sets the Vector2 coordinates with the given floats
  2285. * @param x defines the first coordinate
  2286. * @param y defines the second coordinate
  2287. * @returns the current updated Vector2
  2288. */
  2289. Vector2.prototype.set = function (x, y) {
  2290. return this.copyFromFloats(x, y);
  2291. };
  2292. /**
  2293. * Add another vector with the current one
  2294. * @param otherVector defines the other vector
  2295. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2296. */
  2297. Vector2.prototype.add = function (otherVector) {
  2298. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2299. };
  2300. /**
  2301. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2302. * @param otherVector defines the other vector
  2303. * @param result defines the target vector
  2304. * @returns the unmodified current Vector2
  2305. */
  2306. Vector2.prototype.addToRef = function (otherVector, result) {
  2307. result.x = this.x + otherVector.x;
  2308. result.y = this.y + otherVector.y;
  2309. return this;
  2310. };
  2311. /**
  2312. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2313. * @param otherVector defines the other vector
  2314. * @returns the current updated Vector2
  2315. */
  2316. Vector2.prototype.addInPlace = function (otherVector) {
  2317. this.x += otherVector.x;
  2318. this.y += otherVector.y;
  2319. return this;
  2320. };
  2321. /**
  2322. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2323. * @param otherVector defines the other vector
  2324. * @returns a new Vector2
  2325. */
  2326. Vector2.prototype.addVector3 = function (otherVector) {
  2327. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2328. };
  2329. /**
  2330. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2331. * @param otherVector defines the other vector
  2332. * @returns a new Vector2
  2333. */
  2334. Vector2.prototype.subtract = function (otherVector) {
  2335. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2336. };
  2337. /**
  2338. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2339. * @param otherVector defines the other vector
  2340. * @param result defines the target vector
  2341. * @returns the unmodified current Vector2
  2342. */
  2343. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2344. result.x = this.x - otherVector.x;
  2345. result.y = this.y - otherVector.y;
  2346. return this;
  2347. };
  2348. /**
  2349. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2350. * @param otherVector defines the other vector
  2351. * @returns the current updated Vector2
  2352. */
  2353. Vector2.prototype.subtractInPlace = function (otherVector) {
  2354. this.x -= otherVector.x;
  2355. this.y -= otherVector.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Multiplies in place the current Vector2 coordinates by the given ones
  2360. * @param otherVector defines the other vector
  2361. * @returns the current updated Vector2
  2362. */
  2363. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2364. this.x *= otherVector.x;
  2365. this.y *= otherVector.y;
  2366. return this;
  2367. };
  2368. /**
  2369. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2370. * @param otherVector defines the other vector
  2371. * @returns a new Vector2
  2372. */
  2373. Vector2.prototype.multiply = function (otherVector) {
  2374. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2375. };
  2376. /**
  2377. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2378. * @param otherVector defines the other vector
  2379. * @param result defines the target vector
  2380. * @returns the unmodified current Vector2
  2381. */
  2382. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2383. result.x = this.x * otherVector.x;
  2384. result.y = this.y * otherVector.y;
  2385. return this;
  2386. };
  2387. /**
  2388. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2389. * @param x defines the first coordinate
  2390. * @param y defines the second coordinate
  2391. * @returns a new Vector2
  2392. */
  2393. Vector2.prototype.multiplyByFloats = function (x, y) {
  2394. return new Vector2(this.x * x, this.y * y);
  2395. };
  2396. /**
  2397. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2398. * @param otherVector defines the other vector
  2399. * @returns a new Vector2
  2400. */
  2401. Vector2.prototype.divide = function (otherVector) {
  2402. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2403. };
  2404. /**
  2405. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2406. * @param otherVector defines the other vector
  2407. * @param result defines the target vector
  2408. * @returns the unmodified current Vector2
  2409. */
  2410. Vector2.prototype.divideToRef = function (otherVector, result) {
  2411. result.x = this.x / otherVector.x;
  2412. result.y = this.y / otherVector.y;
  2413. return this;
  2414. };
  2415. /**
  2416. * Divides the current Vector2 coordinates by the given ones
  2417. * @param otherVector defines the other vector
  2418. * @returns the current updated Vector2
  2419. */
  2420. Vector2.prototype.divideInPlace = function (otherVector) {
  2421. return this.divideToRef(otherVector, this);
  2422. };
  2423. /**
  2424. * Gets a new Vector2 with current Vector2 negated coordinates
  2425. * @returns a new Vector2
  2426. */
  2427. Vector2.prototype.negate = function () {
  2428. return new Vector2(-this.x, -this.y);
  2429. };
  2430. /**
  2431. * Multiply the Vector2 coordinates by scale
  2432. * @param scale defines the scaling factor
  2433. * @returns the current updated Vector2
  2434. */
  2435. Vector2.prototype.scaleInPlace = function (scale) {
  2436. this.x *= scale;
  2437. this.y *= scale;
  2438. return this;
  2439. };
  2440. /**
  2441. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2442. * @param scale defines the scaling factor
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.scale = function (scale) {
  2446. var result = new Vector2(0, 0);
  2447. this.scaleToRef(scale, result);
  2448. return result;
  2449. };
  2450. /**
  2451. * Scale the current Vector2 values by a factor to a given Vector2
  2452. * @param scale defines the scale factor
  2453. * @param result defines the Vector2 object where to store the result
  2454. * @returns the unmodified current Vector2
  2455. */
  2456. Vector2.prototype.scaleToRef = function (scale, result) {
  2457. result.x = this.x * scale;
  2458. result.y = this.y * scale;
  2459. return this;
  2460. };
  2461. /**
  2462. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2463. * @param scale defines the scale factor
  2464. * @param result defines the Vector2 object where to store the result
  2465. * @returns the unmodified current Vector2
  2466. */
  2467. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2468. result.x += this.x * scale;
  2469. result.y += this.y * scale;
  2470. return this;
  2471. };
  2472. /**
  2473. * Gets a boolean if two vectors are equals
  2474. * @param otherVector defines the other vector
  2475. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2476. */
  2477. Vector2.prototype.equals = function (otherVector) {
  2478. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2479. };
  2480. /**
  2481. * Gets a boolean if two vectors are equals (using an epsilon value)
  2482. * @param otherVector defines the other vector
  2483. * @param epsilon defines the minimal distance to consider equality
  2484. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2485. */
  2486. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2487. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2488. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2489. };
  2490. /**
  2491. * Gets a new Vector2 from current Vector2 floored values
  2492. * @returns a new Vector2
  2493. */
  2494. Vector2.prototype.floor = function () {
  2495. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2496. };
  2497. /**
  2498. * Gets a new Vector2 from current Vector2 floored values
  2499. * @returns a new Vector2
  2500. */
  2501. Vector2.prototype.fract = function () {
  2502. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2503. };
  2504. // Properties
  2505. /**
  2506. * Gets the length of the vector
  2507. * @returns the vector length (float)
  2508. */
  2509. Vector2.prototype.length = function () {
  2510. return Math.sqrt(this.x * this.x + this.y * this.y);
  2511. };
  2512. /**
  2513. * Gets the vector squared length
  2514. * @returns the vector squared length (float)
  2515. */
  2516. Vector2.prototype.lengthSquared = function () {
  2517. return (this.x * this.x + this.y * this.y);
  2518. };
  2519. // Methods
  2520. /**
  2521. * Normalize the vector
  2522. * @returns the current updated Vector2
  2523. */
  2524. Vector2.prototype.normalize = function () {
  2525. var len = this.length();
  2526. if (len === 0)
  2527. return this;
  2528. var num = 1.0 / len;
  2529. this.x *= num;
  2530. this.y *= num;
  2531. return this;
  2532. };
  2533. /**
  2534. * Gets a new Vector2 copied from the Vector2
  2535. * @returns a new Vector2
  2536. */
  2537. Vector2.prototype.clone = function () {
  2538. return new Vector2(this.x, this.y);
  2539. };
  2540. // Statics
  2541. /**
  2542. * Gets a new Vector2(0, 0)
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.Zero = function () {
  2546. return new Vector2(0, 0);
  2547. };
  2548. /**
  2549. * Gets a new Vector2(1, 1)
  2550. * @returns a new Vector2
  2551. */
  2552. Vector2.One = function () {
  2553. return new Vector2(1, 1);
  2554. };
  2555. /**
  2556. * Gets a new Vector2 set from the given index element of the given array
  2557. * @param array defines the data source
  2558. * @param offset defines the offset in the data source
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.FromArray = function (array, offset) {
  2562. if (offset === void 0) { offset = 0; }
  2563. return new Vector2(array[offset], array[offset + 1]);
  2564. };
  2565. /**
  2566. * Sets "result" from the given index element of the given array
  2567. * @param array defines the data source
  2568. * @param offset defines the offset in the data source
  2569. * @param result defines the target vector
  2570. */
  2571. Vector2.FromArrayToRef = function (array, offset, result) {
  2572. result.x = array[offset];
  2573. result.y = array[offset + 1];
  2574. };
  2575. /**
  2576. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2577. * @param value1 defines 1st point of control
  2578. * @param value2 defines 2nd point of control
  2579. * @param value3 defines 3rd point of control
  2580. * @param value4 defines 4th point of control
  2581. * @param amount defines the interpolation factor
  2582. * @returns a new Vector2
  2583. */
  2584. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2585. var squared = amount * amount;
  2586. var cubed = amount * squared;
  2587. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2588. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2589. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2590. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2591. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2592. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2593. return new Vector2(x, y);
  2594. };
  2595. /**
  2596. * 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".
  2597. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2598. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2599. * @param value defines the value to clamp
  2600. * @param min defines the lower limit
  2601. * @param max defines the upper limit
  2602. * @returns a new Vector2
  2603. */
  2604. Vector2.Clamp = function (value, min, max) {
  2605. var x = value.x;
  2606. x = (x > max.x) ? max.x : x;
  2607. x = (x < min.x) ? min.x : x;
  2608. var y = value.y;
  2609. y = (y > max.y) ? max.y : y;
  2610. y = (y < min.y) ? min.y : y;
  2611. return new Vector2(x, y);
  2612. };
  2613. /**
  2614. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2615. * @param value1 defines the 1st control point
  2616. * @param tangent1 defines the outgoing tangent
  2617. * @param value2 defines the 2nd control point
  2618. * @param tangent2 defines the incoming tangent
  2619. * @param amount defines the interpolation factor
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2623. var squared = amount * amount;
  2624. var cubed = amount * squared;
  2625. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2626. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2627. var part3 = (cubed - (2.0 * squared)) + amount;
  2628. var part4 = cubed - squared;
  2629. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2630. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2631. return new Vector2(x, y);
  2632. };
  2633. /**
  2634. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2635. * @param start defines the start vector
  2636. * @param end defines the end vector
  2637. * @param amount defines the interpolation factor
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Lerp = function (start, end, amount) {
  2641. var x = start.x + ((end.x - start.x) * amount);
  2642. var y = start.y + ((end.y - start.y) * amount);
  2643. return new Vector2(x, y);
  2644. };
  2645. /**
  2646. * Gets the dot product of the vector "left" and the vector "right"
  2647. * @param left defines first vector
  2648. * @param right defines second vector
  2649. * @returns the dot product (float)
  2650. */
  2651. Vector2.Dot = function (left, right) {
  2652. return left.x * right.x + left.y * right.y;
  2653. };
  2654. /**
  2655. * Returns a new Vector2 equal to the normalized given vector
  2656. * @param vector defines the vector to normalize
  2657. * @returns a new Vector2
  2658. */
  2659. Vector2.Normalize = function (vector) {
  2660. var newVector = vector.clone();
  2661. newVector.normalize();
  2662. return newVector;
  2663. };
  2664. /**
  2665. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2666. * @param left defines 1st vector
  2667. * @param right defines 2nd vector
  2668. * @returns a new Vector2
  2669. */
  2670. Vector2.Minimize = function (left, right) {
  2671. var x = (left.x < right.x) ? left.x : right.x;
  2672. var y = (left.y < right.y) ? left.y : right.y;
  2673. return new Vector2(x, y);
  2674. };
  2675. /**
  2676. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2677. * @param left defines 1st vector
  2678. * @param right defines 2nd vector
  2679. * @returns a new Vector2
  2680. */
  2681. Vector2.Maximize = function (left, right) {
  2682. var x = (left.x > right.x) ? left.x : right.x;
  2683. var y = (left.y > right.y) ? left.y : right.y;
  2684. return new Vector2(x, y);
  2685. };
  2686. /**
  2687. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2688. * @param vector defines the vector to transform
  2689. * @param transformation defines the matrix to apply
  2690. * @returns a new Vector2
  2691. */
  2692. Vector2.Transform = function (vector, transformation) {
  2693. var r = Vector2.Zero();
  2694. Vector2.TransformToRef(vector, transformation, r);
  2695. return r;
  2696. };
  2697. /**
  2698. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2699. * @param vector defines the vector to transform
  2700. * @param transformation defines the matrix to apply
  2701. * @param result defines the target vector
  2702. */
  2703. Vector2.TransformToRef = function (vector, transformation, result) {
  2704. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2705. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2706. result.x = x;
  2707. result.y = y;
  2708. };
  2709. /**
  2710. * Determines if a given vector is included in a triangle
  2711. * @param p defines the vector to test
  2712. * @param p0 defines 1st triangle point
  2713. * @param p1 defines 2nd triangle point
  2714. * @param p2 defines 3rd triangle point
  2715. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2716. */
  2717. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2718. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2719. var sign = a < 0 ? -1 : 1;
  2720. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2721. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2722. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2723. };
  2724. /**
  2725. * Gets the distance between the vectors "value1" and "value2"
  2726. * @param value1 defines first vector
  2727. * @param value2 defines second vector
  2728. * @returns the distance between vectors
  2729. */
  2730. Vector2.Distance = function (value1, value2) {
  2731. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2732. };
  2733. /**
  2734. * Returns the squared distance between the vectors "value1" and "value2"
  2735. * @param value1 defines first vector
  2736. * @param value2 defines second vector
  2737. * @returns the squared distance between vectors
  2738. */
  2739. Vector2.DistanceSquared = function (value1, value2) {
  2740. var x = value1.x - value2.x;
  2741. var y = value1.y - value2.y;
  2742. return (x * x) + (y * y);
  2743. };
  2744. /**
  2745. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2746. * @param value1 defines first vector
  2747. * @param value2 defines second vector
  2748. * @returns a new Vector2
  2749. */
  2750. Vector2.Center = function (value1, value2) {
  2751. var center = value1.add(value2);
  2752. center.scaleInPlace(0.5);
  2753. return center;
  2754. };
  2755. /**
  2756. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2757. * @param p defines the middle point
  2758. * @param segA defines one point of the segment
  2759. * @param segB defines the other point of the segment
  2760. * @returns the shortest distance
  2761. */
  2762. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2763. var l2 = Vector2.DistanceSquared(segA, segB);
  2764. if (l2 === 0.0) {
  2765. return Vector2.Distance(p, segA);
  2766. }
  2767. var v = segB.subtract(segA);
  2768. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2769. var proj = segA.add(v.multiplyByFloats(t, t));
  2770. return Vector2.Distance(p, proj);
  2771. };
  2772. return Vector2;
  2773. }());
  2774. BABYLON.Vector2 = Vector2;
  2775. /**
  2776. * Classed used to store (x,y,z) vector representation
  2777. * A Vector3 is the main object used in 3D geometry
  2778. * It can represent etiher the coordinates of a point the space, either a direction
  2779. * Reminder: Babylon.js uses a left handed forward facing system
  2780. */
  2781. var Vector3 = /** @class */ (function () {
  2782. /**
  2783. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2784. * @param x defines the first coordinates (on X axis)
  2785. * @param y defines the second coordinates (on Y axis)
  2786. * @param z defines the third coordinates (on Z axis)
  2787. */
  2788. function Vector3(
  2789. /**
  2790. * Defines the first coordinates (on X axis)
  2791. */
  2792. x,
  2793. /**
  2794. * Defines the second coordinates (on Y axis)
  2795. */
  2796. y,
  2797. /**
  2798. * Defines the third coordinates (on Z axis)
  2799. */
  2800. z) {
  2801. if (x === void 0) { x = 0; }
  2802. if (y === void 0) { y = 0; }
  2803. if (z === void 0) { z = 0; }
  2804. this.x = x;
  2805. this.y = y;
  2806. this.z = z;
  2807. }
  2808. /**
  2809. * Creates a string representation of the Vector3
  2810. * @returns a string with the Vector3 coordinates.
  2811. */
  2812. Vector3.prototype.toString = function () {
  2813. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2814. };
  2815. /**
  2816. * Gets the class name
  2817. * @returns the string "Vector3"
  2818. */
  2819. Vector3.prototype.getClassName = function () {
  2820. return "Vector3";
  2821. };
  2822. /**
  2823. * Creates the Vector3 hash code
  2824. * @returns a number which tends to be unique between Vector3 instances
  2825. */
  2826. Vector3.prototype.getHashCode = function () {
  2827. var hash = this.x || 0;
  2828. hash = (hash * 397) ^ (this.y || 0);
  2829. hash = (hash * 397) ^ (this.z || 0);
  2830. return hash;
  2831. };
  2832. // Operators
  2833. /**
  2834. * Creates an array containing three elements : the coordinates of the Vector3
  2835. * @returns a new array of numbers
  2836. */
  2837. Vector3.prototype.asArray = function () {
  2838. var result = [];
  2839. this.toArray(result, 0);
  2840. return result;
  2841. };
  2842. /**
  2843. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2844. * @param array defines the destination array
  2845. * @param index defines the offset in the destination array
  2846. * @returns the current Vector3
  2847. */
  2848. Vector3.prototype.toArray = function (array, index) {
  2849. if (index === void 0) { index = 0; }
  2850. array[index] = this.x;
  2851. array[index + 1] = this.y;
  2852. array[index + 2] = this.z;
  2853. return this;
  2854. };
  2855. /**
  2856. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2857. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2858. */
  2859. Vector3.prototype.toQuaternion = function () {
  2860. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2861. };
  2862. /**
  2863. * Adds the given vector to the current Vector3
  2864. * @param otherVector defines the second operand
  2865. * @returns the current updated Vector3
  2866. */
  2867. Vector3.prototype.addInPlace = function (otherVector) {
  2868. this.x += otherVector.x;
  2869. this.y += otherVector.y;
  2870. this.z += otherVector.z;
  2871. return this;
  2872. };
  2873. /**
  2874. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2875. * @param otherVector defines the second operand
  2876. * @returns the resulting Vector3
  2877. */
  2878. Vector3.prototype.add = function (otherVector) {
  2879. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2880. };
  2881. /**
  2882. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2883. * @param otherVector defines the second operand
  2884. * @param result defines the Vector3 object where to store the result
  2885. * @returns the current Vector3
  2886. */
  2887. Vector3.prototype.addToRef = function (otherVector, result) {
  2888. result.x = this.x + otherVector.x;
  2889. result.y = this.y + otherVector.y;
  2890. result.z = this.z + otherVector.z;
  2891. return this;
  2892. };
  2893. /**
  2894. * Subtract the given vector from the current Vector3
  2895. * @param otherVector defines the second operand
  2896. * @returns the current updated Vector3
  2897. */
  2898. Vector3.prototype.subtractInPlace = function (otherVector) {
  2899. this.x -= otherVector.x;
  2900. this.y -= otherVector.y;
  2901. this.z -= otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2906. * @param otherVector defines the second operand
  2907. * @returns the resulting Vector3
  2908. */
  2909. Vector3.prototype.subtract = function (otherVector) {
  2910. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2911. };
  2912. /**
  2913. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2914. * @param otherVector defines the second operand
  2915. * @param result defines the Vector3 object where to store the result
  2916. * @returns the current Vector3
  2917. */
  2918. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2919. result.x = this.x - otherVector.x;
  2920. result.y = this.y - otherVector.y;
  2921. result.z = this.z - otherVector.z;
  2922. return this;
  2923. };
  2924. /**
  2925. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2926. * @param x defines the x coordinate of the operand
  2927. * @param y defines the y coordinate of the operand
  2928. * @param z defines the z coordinate of the operand
  2929. * @returns the resulting Vector3
  2930. */
  2931. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2932. return new Vector3(this.x - x, this.y - y, this.z - z);
  2933. };
  2934. /**
  2935. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2936. * @param x defines the x coordinate of the operand
  2937. * @param y defines the y coordinate of the operand
  2938. * @param z defines the z coordinate of the operand
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the current Vector3
  2941. */
  2942. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2943. result.x = this.x - x;
  2944. result.y = this.y - y;
  2945. result.z = this.z - z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2950. * @returns a new Vector3
  2951. */
  2952. Vector3.prototype.negate = function () {
  2953. return new Vector3(-this.x, -this.y, -this.z);
  2954. };
  2955. /**
  2956. * Multiplies the Vector3 coordinates by the float "scale"
  2957. * @param scale defines the multiplier factor
  2958. * @returns the current updated Vector3
  2959. */
  2960. Vector3.prototype.scaleInPlace = function (scale) {
  2961. this.x *= scale;
  2962. this.y *= scale;
  2963. this.z *= scale;
  2964. return this;
  2965. };
  2966. /**
  2967. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2968. * @param scale defines the multiplier factor
  2969. * @returns a new Vector3
  2970. */
  2971. Vector3.prototype.scale = function (scale) {
  2972. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2973. };
  2974. /**
  2975. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2976. * @param scale defines the multiplier factor
  2977. * @param result defines the Vector3 object where to store the result
  2978. * @returns the current Vector3
  2979. */
  2980. Vector3.prototype.scaleToRef = function (scale, result) {
  2981. result.x = this.x * scale;
  2982. result.y = this.y * scale;
  2983. result.z = this.z * scale;
  2984. return this;
  2985. };
  2986. /**
  2987. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2988. * @param scale defines the scale factor
  2989. * @param result defines the Vector3 object where to store the result
  2990. * @returns the unmodified current Vector3
  2991. */
  2992. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2993. result.x += this.x * scale;
  2994. result.y += this.y * scale;
  2995. result.z += this.z * scale;
  2996. return this;
  2997. };
  2998. /**
  2999. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3000. * @param otherVector defines the second operand
  3001. * @returns true if both vectors are equals
  3002. */
  3003. Vector3.prototype.equals = function (otherVector) {
  3004. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3005. };
  3006. /**
  3007. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3008. * @param otherVector defines the second operand
  3009. * @param epsilon defines the minimal distance to define values as equals
  3010. * @returns true if both vectors are distant less than epsilon
  3011. */
  3012. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3013. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3014. 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);
  3015. };
  3016. /**
  3017. * Returns true if the current Vector3 coordinates equals the given floats
  3018. * @param x defines the x coordinate of the operand
  3019. * @param y defines the y coordinate of the operand
  3020. * @param z defines the z coordinate of the operand
  3021. * @returns true if both vectors are equals
  3022. */
  3023. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3024. return this.x === x && this.y === y && this.z === z;
  3025. };
  3026. /**
  3027. * Multiplies the current Vector3 coordinates by the given ones
  3028. * @param otherVector defines the second operand
  3029. * @returns the current updated Vector3
  3030. */
  3031. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3032. this.x *= otherVector.x;
  3033. this.y *= otherVector.y;
  3034. this.z *= otherVector.z;
  3035. return this;
  3036. };
  3037. /**
  3038. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3039. * @param otherVector defines the second operand
  3040. * @returns the new Vector3
  3041. */
  3042. Vector3.prototype.multiply = function (otherVector) {
  3043. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3044. };
  3045. /**
  3046. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3047. * @param otherVector defines the second operand
  3048. * @param result defines the Vector3 object where to store the result
  3049. * @returns the current Vector3
  3050. */
  3051. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3052. result.x = this.x * otherVector.x;
  3053. result.y = this.y * otherVector.y;
  3054. result.z = this.z * otherVector.z;
  3055. return this;
  3056. };
  3057. /**
  3058. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3059. * @param x defines the x coordinate of the operand
  3060. * @param y defines the y coordinate of the operand
  3061. * @param z defines the z coordinate of the operand
  3062. * @returns the new Vector3
  3063. */
  3064. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3065. return new Vector3(this.x * x, this.y * y, this.z * z);
  3066. };
  3067. /**
  3068. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3069. * @param otherVector defines the second operand
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.prototype.divide = function (otherVector) {
  3073. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3074. };
  3075. /**
  3076. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3077. * @param otherVector defines the second operand
  3078. * @param result defines the Vector3 object where to store the result
  3079. * @returns the current Vector3
  3080. */
  3081. Vector3.prototype.divideToRef = function (otherVector, result) {
  3082. result.x = this.x / otherVector.x;
  3083. result.y = this.y / otherVector.y;
  3084. result.z = this.z / otherVector.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Divides the current Vector3 coordinates by the given ones.
  3089. * @param otherVector defines the second operand
  3090. * @returns the current updated Vector3
  3091. */
  3092. Vector3.prototype.divideInPlace = function (otherVector) {
  3093. return this.divideToRef(otherVector, this);
  3094. };
  3095. /**
  3096. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3097. * @param other defines the second operand
  3098. * @returns the current updated Vector3
  3099. */
  3100. Vector3.prototype.minimizeInPlace = function (other) {
  3101. if (other.x < this.x)
  3102. this.x = other.x;
  3103. if (other.y < this.y)
  3104. this.y = other.y;
  3105. if (other.z < this.z)
  3106. this.z = other.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3111. * @param other defines the second operand
  3112. * @returns the current updated Vector3
  3113. */
  3114. Vector3.prototype.maximizeInPlace = function (other) {
  3115. if (other.x > this.x)
  3116. this.x = other.x;
  3117. if (other.y > this.y)
  3118. this.y = other.y;
  3119. if (other.z > this.z)
  3120. this.z = other.z;
  3121. return this;
  3122. };
  3123. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3124. /**
  3125. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3126. */
  3127. get: function () {
  3128. var absX = Math.abs(this.x);
  3129. var absY = Math.abs(this.y);
  3130. if (absX !== absY) {
  3131. return true;
  3132. }
  3133. var absZ = Math.abs(this.z);
  3134. if (absX !== absZ) {
  3135. return true;
  3136. }
  3137. if (absY !== absZ) {
  3138. return true;
  3139. }
  3140. return false;
  3141. },
  3142. enumerable: true,
  3143. configurable: true
  3144. });
  3145. /**
  3146. * Gets a new Vector3 from current Vector3 floored values
  3147. * @returns a new Vector3
  3148. */
  3149. Vector3.prototype.floor = function () {
  3150. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3151. };
  3152. /**
  3153. * Gets a new Vector3 from current Vector3 floored values
  3154. * @returns a new Vector3
  3155. */
  3156. Vector3.prototype.fract = function () {
  3157. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3158. };
  3159. // Properties
  3160. /**
  3161. * Gets the length of the Vector3
  3162. * @returns the length of the Vecto3
  3163. */
  3164. Vector3.prototype.length = function () {
  3165. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3166. };
  3167. /**
  3168. * Gets the squared length of the Vector3
  3169. * @returns squared length of the Vector3
  3170. */
  3171. Vector3.prototype.lengthSquared = function () {
  3172. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3173. };
  3174. /**
  3175. * Normalize the current Vector3.
  3176. * Please note that this is an in place operation.
  3177. * @returns the current updated Vector3
  3178. */
  3179. Vector3.prototype.normalize = function () {
  3180. var len = this.length();
  3181. if (len === 0 || len === 1.0)
  3182. return this;
  3183. var num = 1.0 / len;
  3184. this.x *= num;
  3185. this.y *= num;
  3186. this.z *= num;
  3187. return this;
  3188. };
  3189. /**
  3190. * Normalize the current Vector3 to a new vector
  3191. * @returns the new Vector3
  3192. */
  3193. Vector3.prototype.normalizeToNew = function () {
  3194. var normalized = new Vector3(0, 0, 0);
  3195. this.normalizeToRef(normalized);
  3196. return normalized;
  3197. };
  3198. /**
  3199. * Normalize the current Vector3 to the reference
  3200. * @param reference define the Vector3 to update
  3201. * @returns the updated Vector3
  3202. */
  3203. Vector3.prototype.normalizeToRef = function (reference) {
  3204. var len = this.length();
  3205. if (len === 0 || len === 1.0) {
  3206. reference.set(this.x, this.y, this.z);
  3207. return reference;
  3208. }
  3209. var scale = 1.0 / len;
  3210. this.scaleToRef(scale, reference);
  3211. return reference;
  3212. };
  3213. /**
  3214. * Creates a new Vector3 copied from the current Vector3
  3215. * @returns the new Vector3
  3216. */
  3217. Vector3.prototype.clone = function () {
  3218. return new Vector3(this.x, this.y, this.z);
  3219. };
  3220. /**
  3221. * Copies the given vector coordinates to the current Vector3 ones
  3222. * @param source defines the source Vector3
  3223. * @returns the current updated Vector3
  3224. */
  3225. Vector3.prototype.copyFrom = function (source) {
  3226. this.x = source.x;
  3227. this.y = source.y;
  3228. this.z = source.z;
  3229. return this;
  3230. };
  3231. /**
  3232. * Copies the given floats to the current Vector3 coordinates
  3233. * @param x defines the x coordinate of the operand
  3234. * @param y defines the y coordinate of the operand
  3235. * @param z defines the z coordinate of the operand
  3236. * @returns the current updated Vector3
  3237. */
  3238. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3239. this.x = x;
  3240. this.y = y;
  3241. this.z = z;
  3242. return this;
  3243. };
  3244. /**
  3245. * Copies the given floats to the current Vector3 coordinates
  3246. * @param x defines the x coordinate of the operand
  3247. * @param y defines the y coordinate of the operand
  3248. * @param z defines the z coordinate of the operand
  3249. * @returns the current updated Vector3
  3250. */
  3251. Vector3.prototype.set = function (x, y, z) {
  3252. return this.copyFromFloats(x, y, z);
  3253. };
  3254. // Statics
  3255. /**
  3256. * Get the clip factor between two vectors
  3257. * @param vector0 defines the first operand
  3258. * @param vector1 defines the second operand
  3259. * @param axis defines the axis to use
  3260. * @param size defines the size along the axis
  3261. * @returns the clip factor
  3262. */
  3263. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3264. var d0 = Vector3.Dot(vector0, axis) - size;
  3265. var d1 = Vector3.Dot(vector1, axis) - size;
  3266. var s = d0 / (d0 - d1);
  3267. return s;
  3268. };
  3269. /**
  3270. * Get angle between two vectors
  3271. * @param vector0 angle between vector0 and vector1
  3272. * @param vector1 angle between vector0 and vector1
  3273. * @param normal direction of the normal
  3274. * @return the angle between vector0 and vector1
  3275. */
  3276. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3277. var v0 = vector0.clone().normalize();
  3278. var v1 = vector1.clone().normalize();
  3279. var dot = Vector3.Dot(v0, v1);
  3280. var n = Vector3.Cross(v0, v1);
  3281. if (Vector3.Dot(n, normal) > 0) {
  3282. return Math.acos(dot);
  3283. }
  3284. return -Math.acos(dot);
  3285. };
  3286. /**
  3287. * Returns a new Vector3 set from the index "offset" of the given array
  3288. * @param array defines the source array
  3289. * @param offset defines the offset in the source array
  3290. * @returns the new Vector3
  3291. */
  3292. Vector3.FromArray = function (array, offset) {
  3293. if (!offset) {
  3294. offset = 0;
  3295. }
  3296. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3297. };
  3298. /**
  3299. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3300. * This function is deprecated. Use FromArray instead
  3301. * @param array defines the source array
  3302. * @param offset defines the offset in the source array
  3303. * @returns the new Vector3
  3304. */
  3305. Vector3.FromFloatArray = function (array, offset) {
  3306. return Vector3.FromArray(array, offset);
  3307. };
  3308. /**
  3309. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3310. * @param array defines the source array
  3311. * @param offset defines the offset in the source array
  3312. * @param result defines the Vector3 where to store the result
  3313. */
  3314. Vector3.FromArrayToRef = function (array, offset, result) {
  3315. result.x = array[offset];
  3316. result.y = array[offset + 1];
  3317. result.z = array[offset + 2];
  3318. };
  3319. /**
  3320. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3321. * This function is deprecated. Use FromArrayToRef instead.
  3322. * @param array defines the source array
  3323. * @param offset defines the offset in the source array
  3324. * @param result defines the Vector3 where to store the result
  3325. */
  3326. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3327. return Vector3.FromArrayToRef(array, offset, result);
  3328. };
  3329. /**
  3330. * Sets the given vector "result" with the given floats.
  3331. * @param x defines the x coordinate of the source
  3332. * @param y defines the y coordinate of the source
  3333. * @param z defines the z coordinate of the source
  3334. * @param result defines the Vector3 where to store the result
  3335. */
  3336. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3337. result.x = x;
  3338. result.y = y;
  3339. result.z = z;
  3340. };
  3341. /**
  3342. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3343. * @returns a new empty Vector3
  3344. */
  3345. Vector3.Zero = function () {
  3346. return new Vector3(0.0, 0.0, 0.0);
  3347. };
  3348. /**
  3349. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3350. * @returns a new unit Vector3
  3351. */
  3352. Vector3.One = function () {
  3353. return new Vector3(1.0, 1.0, 1.0);
  3354. };
  3355. /**
  3356. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3357. * @returns a new up Vector3
  3358. */
  3359. Vector3.Up = function () {
  3360. return new Vector3(0.0, 1.0, 0.0);
  3361. };
  3362. /**
  3363. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3364. * @returns a new down Vector3
  3365. */
  3366. Vector3.Down = function () {
  3367. return new Vector3(0.0, -1.0, 0.0);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3371. * @returns a new forward Vector3
  3372. */
  3373. Vector3.Forward = function () {
  3374. return new Vector3(0.0, 0.0, 1.0);
  3375. };
  3376. /**
  3377. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3378. * @returns a new right Vector3
  3379. */
  3380. Vector3.Right = function () {
  3381. return new Vector3(1.0, 0.0, 0.0);
  3382. };
  3383. /**
  3384. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3385. * @returns a new left Vector3
  3386. */
  3387. Vector3.Left = function () {
  3388. return new Vector3(-1.0, 0.0, 0.0);
  3389. };
  3390. /**
  3391. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3392. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3393. * @param vector defines the Vector3 to transform
  3394. * @param transformation defines the transformation matrix
  3395. * @returns the transformed Vector3
  3396. */
  3397. Vector3.TransformCoordinates = function (vector, transformation) {
  3398. var result = Vector3.Zero();
  3399. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3400. return result;
  3401. };
  3402. /**
  3403. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3404. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3405. * @param vector defines the Vector3 to transform
  3406. * @param transformation defines the transformation matrix
  3407. * @param result defines the Vector3 where to store the result
  3408. */
  3409. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3410. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3411. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3412. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3413. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3414. result.x = x / w;
  3415. result.y = y / w;
  3416. result.z = z / w;
  3417. };
  3418. /**
  3419. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3420. * This method computes tranformed coordinates only, not transformed direction vectors
  3421. * @param x define the x coordinate of the source vector
  3422. * @param y define the y coordinate of the source vector
  3423. * @param z define the z coordinate of the source vector
  3424. * @param transformation defines the transformation matrix
  3425. * @param result defines the Vector3 where to store the result
  3426. */
  3427. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3428. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3429. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3430. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3431. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3432. result.x = rx / rw;
  3433. result.y = ry / rw;
  3434. result.z = rz / rw;
  3435. };
  3436. /**
  3437. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3438. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3439. * @param vector defines the Vector3 to transform
  3440. * @param transformation defines the transformation matrix
  3441. * @returns the new Vector3
  3442. */
  3443. Vector3.TransformNormal = function (vector, transformation) {
  3444. var result = Vector3.Zero();
  3445. Vector3.TransformNormalToRef(vector, transformation, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3450. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @param result defines the Vector3 where to store the result
  3454. */
  3455. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3456. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3457. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3458. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3459. result.x = x;
  3460. result.y = y;
  3461. result.z = z;
  3462. };
  3463. /**
  3464. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3465. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3466. * @param x define the x coordinate of the source vector
  3467. * @param y define the y coordinate of the source vector
  3468. * @param z define the z coordinate of the source vector
  3469. * @param transformation defines the transformation matrix
  3470. * @param result defines the Vector3 where to store the result
  3471. */
  3472. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3473. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3474. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3475. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3476. };
  3477. /**
  3478. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3479. * @param value1 defines the first control point
  3480. * @param value2 defines the second control point
  3481. * @param value3 defines the third control point
  3482. * @param value4 defines the fourth control point
  3483. * @param amount defines the amount on the spline to use
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3487. var squared = amount * amount;
  3488. var cubed = amount * squared;
  3489. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3490. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3491. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3492. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3493. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3494. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3495. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3496. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3497. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3498. return new Vector3(x, y, z);
  3499. };
  3500. /**
  3501. * 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"
  3502. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3503. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3504. * @param value defines the current value
  3505. * @param min defines the lower range value
  3506. * @param max defines the upper range value
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Clamp = function (value, min, max) {
  3510. var x = value.x;
  3511. x = (x > max.x) ? max.x : x;
  3512. x = (x < min.x) ? min.x : x;
  3513. var y = value.y;
  3514. y = (y > max.y) ? max.y : y;
  3515. y = (y < min.y) ? min.y : y;
  3516. var z = value.z;
  3517. z = (z > max.z) ? max.z : z;
  3518. z = (z < min.z) ? min.z : z;
  3519. return new Vector3(x, y, z);
  3520. };
  3521. /**
  3522. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3523. * @param value1 defines the first control point
  3524. * @param tangent1 defines the first tangent vector
  3525. * @param value2 defines the second control point
  3526. * @param tangent2 defines the second tangent vector
  3527. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3528. * @returns the new Vector3
  3529. */
  3530. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3531. var squared = amount * amount;
  3532. var cubed = amount * squared;
  3533. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3534. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3535. var part3 = (cubed - (2.0 * squared)) + amount;
  3536. var part4 = cubed - squared;
  3537. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3538. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3539. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3540. return new Vector3(x, y, z);
  3541. };
  3542. /**
  3543. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3544. * @param start defines the start value
  3545. * @param end defines the end value
  3546. * @param amount max defines amount between both (between 0 and 1)
  3547. * @returns the new Vector3
  3548. */
  3549. Vector3.Lerp = function (start, end, amount) {
  3550. var result = new Vector3(0, 0, 0);
  3551. Vector3.LerpToRef(start, end, amount, result);
  3552. return result;
  3553. };
  3554. /**
  3555. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3556. * @param start defines the start value
  3557. * @param end defines the end value
  3558. * @param amount max defines amount between both (between 0 and 1)
  3559. * @param result defines the Vector3 where to store the result
  3560. */
  3561. Vector3.LerpToRef = function (start, end, amount, result) {
  3562. result.x = start.x + ((end.x - start.x) * amount);
  3563. result.y = start.y + ((end.y - start.y) * amount);
  3564. result.z = start.z + ((end.z - start.z) * amount);
  3565. };
  3566. /**
  3567. * Returns the dot product (float) between the vectors "left" and "right"
  3568. * @param left defines the left operand
  3569. * @param right defines the right operand
  3570. * @returns the dot product
  3571. */
  3572. Vector3.Dot = function (left, right) {
  3573. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3574. };
  3575. /**
  3576. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3577. * The cross product is then orthogonal to both "left" and "right"
  3578. * @param left defines the left operand
  3579. * @param right defines the right operand
  3580. * @returns the cross product
  3581. */
  3582. Vector3.Cross = function (left, right) {
  3583. var result = Vector3.Zero();
  3584. Vector3.CrossToRef(left, right, result);
  3585. return result;
  3586. };
  3587. /**
  3588. * Sets the given vector "result" with the cross product of "left" and "right"
  3589. * The cross product is then orthogonal to both "left" and "right"
  3590. * @param left defines the left operand
  3591. * @param right defines the right operand
  3592. * @param result defines the Vector3 where to store the result
  3593. */
  3594. Vector3.CrossToRef = function (left, right, result) {
  3595. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3596. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3597. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3598. result.copyFrom(MathTmp.Vector3[0]);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 as the normalization of the given vector
  3602. * @param vector defines the Vector3 to normalize
  3603. * @returns the new Vector3
  3604. */
  3605. Vector3.Normalize = function (vector) {
  3606. var result = Vector3.Zero();
  3607. Vector3.NormalizeToRef(vector, result);
  3608. return result;
  3609. };
  3610. /**
  3611. * Sets the given vector "result" with the normalization of the given first vector
  3612. * @param vector defines the Vector3 to normalize
  3613. * @param result defines the Vector3 where to store the result
  3614. */
  3615. Vector3.NormalizeToRef = function (vector, result) {
  3616. result.copyFrom(vector);
  3617. result.normalize();
  3618. };
  3619. /**
  3620. * Project a Vector3 onto screen space
  3621. * @param vector defines the Vector3 to project
  3622. * @param world defines the world matrix to use
  3623. * @param transform defines the transform (view x projection) matrix to use
  3624. * @param viewport defines the screen viewport to use
  3625. * @returns the new Vector3
  3626. */
  3627. Vector3.Project = function (vector, world, transform, viewport) {
  3628. var cw = viewport.width;
  3629. var ch = viewport.height;
  3630. var cx = viewport.x;
  3631. var cy = viewport.y;
  3632. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3633. 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);
  3634. var matrix = MathTmp.Matrix[0];
  3635. world.multiplyToRef(transform, matrix);
  3636. matrix.multiplyToRef(viewportMatrix, matrix);
  3637. return Vector3.TransformCoordinates(vector, matrix);
  3638. };
  3639. /**
  3640. * Unproject from screen space to object space
  3641. * @param source defines the screen space Vector3 to use
  3642. * @param viewportWidth defines the current width of the viewport
  3643. * @param viewportHeight defines the current height of the viewport
  3644. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3645. * @param transform defines the transform (view x projection) matrix to use
  3646. * @returns the new Vector3
  3647. */
  3648. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3649. var matrix = MathTmp.Matrix[0];
  3650. world.multiplyToRef(transform, matrix);
  3651. matrix.invert();
  3652. source.x = source.x / viewportWidth * 2 - 1;
  3653. source.y = -(source.y / viewportHeight * 2 - 1);
  3654. var vector = Vector3.TransformCoordinates(source, matrix);
  3655. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3656. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3657. vector = vector.scale(1.0 / num);
  3658. }
  3659. return vector;
  3660. };
  3661. /**
  3662. * Unproject from screen space to object space
  3663. * @param source defines the screen space Vector3 to use
  3664. * @param viewportWidth defines the current width of the viewport
  3665. * @param viewportHeight defines the current height of the viewport
  3666. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3667. * @param view defines the view matrix to use
  3668. * @param projection defines the projection matrix to use
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3672. var result = Vector3.Zero();
  3673. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3674. return result;
  3675. };
  3676. /**
  3677. * Unproject from screen space to object space
  3678. * @param source defines the screen space Vector3 to use
  3679. * @param viewportWidth defines the current width of the viewport
  3680. * @param viewportHeight defines the current height of the viewport
  3681. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3682. * @param view defines the view matrix to use
  3683. * @param projection defines the projection matrix to use
  3684. * @param result defines the Vector3 where to store the result
  3685. */
  3686. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3687. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3688. };
  3689. /**
  3690. * Unproject from screen space to object space
  3691. * @param sourceX defines the screen space x coordinate to use
  3692. * @param sourceY defines the screen space y coordinate to use
  3693. * @param sourceZ defines the screen space z coordinate to use
  3694. * @param viewportWidth defines the current width of the viewport
  3695. * @param viewportHeight defines the current height of the viewport
  3696. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3697. * @param view defines the view matrix to use
  3698. * @param projection defines the projection matrix to use
  3699. * @param result defines the Vector3 where to store the result
  3700. */
  3701. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3702. var matrix = MathTmp.Matrix[0];
  3703. world.multiplyToRef(view, matrix);
  3704. matrix.multiplyToRef(projection, matrix);
  3705. matrix.invert();
  3706. var screenSource = MathTmp.Vector3[0];
  3707. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3708. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3709. screenSource.z = 2 * sourceZ - 1.0;
  3710. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3711. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3712. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3713. result.scaleInPlace(1.0 / num);
  3714. }
  3715. };
  3716. /**
  3717. * Gets the minimal coordinate values between two Vector3
  3718. * @param left defines the first operand
  3719. * @param right defines the second operand
  3720. * @returns the new Vector3
  3721. */
  3722. Vector3.Minimize = function (left, right) {
  3723. var min = left.clone();
  3724. min.minimizeInPlace(right);
  3725. return min;
  3726. };
  3727. /**
  3728. * Gets the maximal coordinate values between two Vector3
  3729. * @param left defines the first operand
  3730. * @param right defines the second operand
  3731. * @returns the new Vector3
  3732. */
  3733. Vector3.Maximize = function (left, right) {
  3734. var max = left.clone();
  3735. max.maximizeInPlace(right);
  3736. return max;
  3737. };
  3738. /**
  3739. * Returns the distance between the vectors "value1" and "value2"
  3740. * @param value1 defines the first operand
  3741. * @param value2 defines the second operand
  3742. * @returns the distance
  3743. */
  3744. Vector3.Distance = function (value1, value2) {
  3745. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3746. };
  3747. /**
  3748. * Returns the squared distance between the vectors "value1" and "value2"
  3749. * @param value1 defines the first operand
  3750. * @param value2 defines the second operand
  3751. * @returns the squared distance
  3752. */
  3753. Vector3.DistanceSquared = function (value1, value2) {
  3754. var x = value1.x - value2.x;
  3755. var y = value1.y - value2.y;
  3756. var z = value1.z - value2.z;
  3757. return (x * x) + (y * y) + (z * z);
  3758. };
  3759. /**
  3760. * Returns a new Vector3 located at the center between "value1" and "value2"
  3761. * @param value1 defines the first operand
  3762. * @param value2 defines the second operand
  3763. * @returns the new Vector3
  3764. */
  3765. Vector3.Center = function (value1, value2) {
  3766. var center = value1.add(value2);
  3767. center.scaleInPlace(0.5);
  3768. return center;
  3769. };
  3770. /**
  3771. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3772. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3773. * to something in order to rotate it from its local system to the given target system
  3774. * Note: axis1, axis2 and axis3 are normalized during this operation
  3775. * @param axis1 defines the first axis
  3776. * @param axis2 defines the second axis
  3777. * @param axis3 defines the third axis
  3778. * @returns a new Vector3
  3779. */
  3780. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3781. var rotation = Vector3.Zero();
  3782. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3783. return rotation;
  3784. };
  3785. /**
  3786. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3787. * @param axis1 defines the first axis
  3788. * @param axis2 defines the second axis
  3789. * @param axis3 defines the third axis
  3790. * @param ref defines the Vector3 where to store the result
  3791. */
  3792. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3793. var quat = MathTmp.Quaternion[0];
  3794. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3795. quat.toEulerAnglesToRef(ref);
  3796. };
  3797. return Vector3;
  3798. }());
  3799. BABYLON.Vector3 = Vector3;
  3800. //Vector4 class created for EulerAngle class conversion to Quaternion
  3801. var Vector4 = /** @class */ (function () {
  3802. /**
  3803. * Creates a Vector4 object from the given floats.
  3804. */
  3805. function Vector4(x, y, z, w) {
  3806. this.x = x;
  3807. this.y = y;
  3808. this.z = z;
  3809. this.w = w;
  3810. }
  3811. /**
  3812. * Returns the string with the Vector4 coordinates.
  3813. */
  3814. Vector4.prototype.toString = function () {
  3815. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3816. };
  3817. /**
  3818. * Returns the string "Vector4".
  3819. */
  3820. Vector4.prototype.getClassName = function () {
  3821. return "Vector4";
  3822. };
  3823. /**
  3824. * Returns the Vector4 hash code.
  3825. */
  3826. Vector4.prototype.getHashCode = function () {
  3827. var hash = this.x || 0;
  3828. hash = (hash * 397) ^ (this.y || 0);
  3829. hash = (hash * 397) ^ (this.z || 0);
  3830. hash = (hash * 397) ^ (this.w || 0);
  3831. return hash;
  3832. };
  3833. // Operators
  3834. /**
  3835. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3836. */
  3837. Vector4.prototype.asArray = function () {
  3838. var result = new Array();
  3839. this.toArray(result, 0);
  3840. return result;
  3841. };
  3842. /**
  3843. * Populates the given array from the given index with the Vector4 coordinates.
  3844. * Returns the Vector4.
  3845. */
  3846. Vector4.prototype.toArray = function (array, index) {
  3847. if (index === undefined) {
  3848. index = 0;
  3849. }
  3850. array[index] = this.x;
  3851. array[index + 1] = this.y;
  3852. array[index + 2] = this.z;
  3853. array[index + 3] = this.w;
  3854. return this;
  3855. };
  3856. /**
  3857. * Adds the given vector to the current Vector4.
  3858. * Returns the updated Vector4.
  3859. */
  3860. Vector4.prototype.addInPlace = function (otherVector) {
  3861. this.x += otherVector.x;
  3862. this.y += otherVector.y;
  3863. this.z += otherVector.z;
  3864. this.w += otherVector.w;
  3865. return this;
  3866. };
  3867. /**
  3868. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3869. */
  3870. Vector4.prototype.add = function (otherVector) {
  3871. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3872. };
  3873. /**
  3874. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3875. * Returns the current Vector4.
  3876. */
  3877. Vector4.prototype.addToRef = function (otherVector, result) {
  3878. result.x = this.x + otherVector.x;
  3879. result.y = this.y + otherVector.y;
  3880. result.z = this.z + otherVector.z;
  3881. result.w = this.w + otherVector.w;
  3882. return this;
  3883. };
  3884. /**
  3885. * Subtract in place the given vector from the current Vector4.
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.subtractInPlace = function (otherVector) {
  3889. this.x -= otherVector.x;
  3890. this.y -= otherVector.y;
  3891. this.z -= otherVector.z;
  3892. this.w -= otherVector.w;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3897. */
  3898. Vector4.prototype.subtract = function (otherVector) {
  3899. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3906. result.x = this.x - otherVector.x;
  3907. result.y = this.y - otherVector.y;
  3908. result.z = this.z - otherVector.z;
  3909. result.w = this.w - otherVector.w;
  3910. return this;
  3911. };
  3912. /**
  3913. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3914. */
  3915. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3916. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3917. };
  3918. /**
  3919. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3920. * Returns the current Vector4.
  3921. */
  3922. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3923. result.x = this.x - x;
  3924. result.y = this.y - y;
  3925. result.z = this.z - z;
  3926. result.w = this.w - w;
  3927. return this;
  3928. };
  3929. /**
  3930. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3931. */
  3932. Vector4.prototype.negate = function () {
  3933. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3934. };
  3935. /**
  3936. * Multiplies the current Vector4 coordinates by scale (float).
  3937. * Returns the updated Vector4.
  3938. */
  3939. Vector4.prototype.scaleInPlace = function (scale) {
  3940. this.x *= scale;
  3941. this.y *= scale;
  3942. this.z *= scale;
  3943. this.w *= scale;
  3944. return this;
  3945. };
  3946. /**
  3947. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3948. */
  3949. Vector4.prototype.scale = function (scale) {
  3950. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3951. };
  3952. /**
  3953. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3954. * Returns the current Vector4.
  3955. */
  3956. Vector4.prototype.scaleToRef = function (scale, result) {
  3957. result.x = this.x * scale;
  3958. result.y = this.y * scale;
  3959. result.z = this.z * scale;
  3960. result.w = this.w * scale;
  3961. return this;
  3962. };
  3963. /**
  3964. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3965. * @param scale defines the scale factor
  3966. * @param result defines the Vector4 object where to store the result
  3967. * @returns the unmodified current Vector4
  3968. */
  3969. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3970. result.x += this.x * scale;
  3971. result.y += this.y * scale;
  3972. result.z += this.z * scale;
  3973. result.w += this.w * scale;
  3974. return this;
  3975. };
  3976. /**
  3977. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3978. */
  3979. Vector4.prototype.equals = function (otherVector) {
  3980. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3981. };
  3982. /**
  3983. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3984. */
  3985. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3986. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3987. return otherVector
  3988. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3989. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3990. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3991. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3992. };
  3993. /**
  3994. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3995. */
  3996. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3997. return this.x === x && this.y === y && this.z === z && this.w === w;
  3998. };
  3999. /**
  4000. * Multiplies in place the current Vector4 by the given one.
  4001. * Returns the updated Vector4.
  4002. */
  4003. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4004. this.x *= otherVector.x;
  4005. this.y *= otherVector.y;
  4006. this.z *= otherVector.z;
  4007. this.w *= otherVector.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4012. */
  4013. Vector4.prototype.multiply = function (otherVector) {
  4014. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4015. };
  4016. /**
  4017. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4018. * Returns the current Vector4.
  4019. */
  4020. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4021. result.x = this.x * otherVector.x;
  4022. result.y = this.y * otherVector.y;
  4023. result.z = this.z * otherVector.z;
  4024. result.w = this.w * otherVector.w;
  4025. return this;
  4026. };
  4027. /**
  4028. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4029. */
  4030. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4031. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4032. };
  4033. /**
  4034. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4035. */
  4036. Vector4.prototype.divide = function (otherVector) {
  4037. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4038. };
  4039. /**
  4040. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4041. * Returns the current Vector4.
  4042. */
  4043. Vector4.prototype.divideToRef = function (otherVector, result) {
  4044. result.x = this.x / otherVector.x;
  4045. result.y = this.y / otherVector.y;
  4046. result.z = this.z / otherVector.z;
  4047. result.w = this.w / otherVector.w;
  4048. return this;
  4049. };
  4050. /**
  4051. * Divides the current Vector3 coordinates by the given ones.
  4052. * @returns the updated Vector3.
  4053. */
  4054. Vector4.prototype.divideInPlace = function (otherVector) {
  4055. return this.divideToRef(otherVector, this);
  4056. };
  4057. /**
  4058. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4059. * @param other defines the second operand
  4060. * @returns the current updated Vector4
  4061. */
  4062. Vector4.prototype.minimizeInPlace = function (other) {
  4063. if (other.x < this.x)
  4064. this.x = other.x;
  4065. if (other.y < this.y)
  4066. this.y = other.y;
  4067. if (other.z < this.z)
  4068. this.z = other.z;
  4069. if (other.w < this.w)
  4070. this.w = other.w;
  4071. return this;
  4072. };
  4073. /**
  4074. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4075. * @param other defines the second operand
  4076. * @returns the current updated Vector4
  4077. */
  4078. Vector4.prototype.maximizeInPlace = function (other) {
  4079. if (other.x > this.x)
  4080. this.x = other.x;
  4081. if (other.y > this.y)
  4082. this.y = other.y;
  4083. if (other.z > this.z)
  4084. this.z = other.z;
  4085. if (other.w > this.w)
  4086. this.w = other.w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Gets a new Vector4 from current Vector4 floored values
  4091. * @returns a new Vector4
  4092. */
  4093. Vector4.prototype.floor = function () {
  4094. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4095. };
  4096. /**
  4097. * Gets a new Vector4 from current Vector3 floored values
  4098. * @returns a new Vector4
  4099. */
  4100. Vector4.prototype.fract = function () {
  4101. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4102. };
  4103. // Properties
  4104. /**
  4105. * Returns the Vector4 length (float).
  4106. */
  4107. Vector4.prototype.length = function () {
  4108. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4109. };
  4110. /**
  4111. * Returns the Vector4 squared length (float).
  4112. */
  4113. Vector4.prototype.lengthSquared = function () {
  4114. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4115. };
  4116. // Methods
  4117. /**
  4118. * Normalizes in place the Vector4.
  4119. * Returns the updated Vector4.
  4120. */
  4121. Vector4.prototype.normalize = function () {
  4122. var len = this.length();
  4123. if (len === 0)
  4124. return this;
  4125. var num = 1.0 / len;
  4126. this.x *= num;
  4127. this.y *= num;
  4128. this.z *= num;
  4129. this.w *= num;
  4130. return this;
  4131. };
  4132. /**
  4133. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4134. */
  4135. Vector4.prototype.toVector3 = function () {
  4136. return new Vector3(this.x, this.y, this.z);
  4137. };
  4138. /**
  4139. * Returns a new Vector4 copied from the current one.
  4140. */
  4141. Vector4.prototype.clone = function () {
  4142. return new Vector4(this.x, this.y, this.z, this.w);
  4143. };
  4144. /**
  4145. * Updates the current Vector4 with the given one coordinates.
  4146. * Returns the updated Vector4.
  4147. */
  4148. Vector4.prototype.copyFrom = function (source) {
  4149. this.x = source.x;
  4150. this.y = source.y;
  4151. this.z = source.z;
  4152. this.w = source.w;
  4153. return this;
  4154. };
  4155. /**
  4156. * Updates the current Vector4 coordinates with the given floats.
  4157. * Returns the updated Vector4.
  4158. */
  4159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4160. this.x = x;
  4161. this.y = y;
  4162. this.z = z;
  4163. this.w = w;
  4164. return this;
  4165. };
  4166. /**
  4167. * Updates the current Vector4 coordinates with the given floats.
  4168. * Returns the updated Vector4.
  4169. */
  4170. Vector4.prototype.set = function (x, y, z, w) {
  4171. return this.copyFromFloats(x, y, z, w);
  4172. };
  4173. // Statics
  4174. /**
  4175. * Returns a new Vector4 set from the starting index of the given array.
  4176. */
  4177. Vector4.FromArray = function (array, offset) {
  4178. if (!offset) {
  4179. offset = 0;
  4180. }
  4181. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4182. };
  4183. /**
  4184. * Updates the given vector "result" from the starting index of the given array.
  4185. */
  4186. Vector4.FromArrayToRef = function (array, offset, result) {
  4187. result.x = array[offset];
  4188. result.y = array[offset + 1];
  4189. result.z = array[offset + 2];
  4190. result.w = array[offset + 3];
  4191. };
  4192. /**
  4193. * Updates the given vector "result" from the starting index of the given Float32Array.
  4194. */
  4195. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4196. Vector4.FromArrayToRef(array, offset, result);
  4197. };
  4198. /**
  4199. * Updates the given vector "result" coordinates from the given floats.
  4200. */
  4201. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4202. result.x = x;
  4203. result.y = y;
  4204. result.z = z;
  4205. result.w = w;
  4206. };
  4207. /**
  4208. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4209. */
  4210. Vector4.Zero = function () {
  4211. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4212. };
  4213. /**
  4214. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4215. */
  4216. Vector4.One = function () {
  4217. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4218. };
  4219. /**
  4220. * Returns a new normalized Vector4 from the given one.
  4221. */
  4222. Vector4.Normalize = function (vector) {
  4223. var result = Vector4.Zero();
  4224. Vector4.NormalizeToRef(vector, result);
  4225. return result;
  4226. };
  4227. /**
  4228. * Updates the given vector "result" from the normalization of the given one.
  4229. */
  4230. Vector4.NormalizeToRef = function (vector, result) {
  4231. result.copyFrom(vector);
  4232. result.normalize();
  4233. };
  4234. Vector4.Minimize = function (left, right) {
  4235. var min = left.clone();
  4236. min.minimizeInPlace(right);
  4237. return min;
  4238. };
  4239. Vector4.Maximize = function (left, right) {
  4240. var max = left.clone();
  4241. max.maximizeInPlace(right);
  4242. return max;
  4243. };
  4244. /**
  4245. * Returns the distance (float) between the vectors "value1" and "value2".
  4246. */
  4247. Vector4.Distance = function (value1, value2) {
  4248. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4249. };
  4250. /**
  4251. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4252. */
  4253. Vector4.DistanceSquared = function (value1, value2) {
  4254. var x = value1.x - value2.x;
  4255. var y = value1.y - value2.y;
  4256. var z = value1.z - value2.z;
  4257. var w = value1.w - value2.w;
  4258. return (x * x) + (y * y) + (z * z) + (w * w);
  4259. };
  4260. /**
  4261. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4262. */
  4263. Vector4.Center = function (value1, value2) {
  4264. var center = value1.add(value2);
  4265. center.scaleInPlace(0.5);
  4266. return center;
  4267. };
  4268. /**
  4269. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4270. * This methods computes transformed normalized direction vectors only.
  4271. */
  4272. Vector4.TransformNormal = function (vector, transformation) {
  4273. var result = Vector4.Zero();
  4274. Vector4.TransformNormalToRef(vector, transformation, result);
  4275. return result;
  4276. };
  4277. /**
  4278. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4279. * This methods computes transformed normalized direction vectors only.
  4280. */
  4281. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4285. result.x = x;
  4286. result.y = y;
  4287. result.z = z;
  4288. result.w = vector.w;
  4289. };
  4290. /**
  4291. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4292. * This methods computes transformed normalized direction vectors only.
  4293. */
  4294. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4295. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4296. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4297. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4298. result.w = w;
  4299. };
  4300. return Vector4;
  4301. }());
  4302. BABYLON.Vector4 = Vector4;
  4303. var Size = /** @class */ (function () {
  4304. /**
  4305. * Creates a Size object from the given width and height (floats).
  4306. */
  4307. function Size(width, height) {
  4308. this.width = width;
  4309. this.height = height;
  4310. }
  4311. // Returns a string with the Size width and height.
  4312. Size.prototype.toString = function () {
  4313. return "{W: " + this.width + ", H: " + this.height + "}";
  4314. };
  4315. /**
  4316. * Returns the string "Size"
  4317. */
  4318. Size.prototype.getClassName = function () {
  4319. return "Size";
  4320. };
  4321. /**
  4322. * Returns the Size hash code.
  4323. */
  4324. Size.prototype.getHashCode = function () {
  4325. var hash = this.width || 0;
  4326. hash = (hash * 397) ^ (this.height || 0);
  4327. return hash;
  4328. };
  4329. /**
  4330. * Updates the current size from the given one.
  4331. * Returns the updated Size.
  4332. */
  4333. Size.prototype.copyFrom = function (src) {
  4334. this.width = src.width;
  4335. this.height = src.height;
  4336. };
  4337. /**
  4338. * Updates in place the current Size from the given floats.
  4339. * Returns the updated Size.
  4340. */
  4341. Size.prototype.copyFromFloats = function (width, height) {
  4342. this.width = width;
  4343. this.height = height;
  4344. return this;
  4345. };
  4346. /**
  4347. * Updates in place the current Size from the given floats.
  4348. * Returns the updated Size.
  4349. */
  4350. Size.prototype.set = function (width, height) {
  4351. return this.copyFromFloats(width, height);
  4352. };
  4353. /**
  4354. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4355. */
  4356. Size.prototype.multiplyByFloats = function (w, h) {
  4357. return new Size(this.width * w, this.height * h);
  4358. };
  4359. /**
  4360. * Returns a new Size copied from the given one.
  4361. */
  4362. Size.prototype.clone = function () {
  4363. return new Size(this.width, this.height);
  4364. };
  4365. /**
  4366. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4367. */
  4368. Size.prototype.equals = function (other) {
  4369. if (!other) {
  4370. return false;
  4371. }
  4372. return (this.width === other.width) && (this.height === other.height);
  4373. };
  4374. Object.defineProperty(Size.prototype, "surface", {
  4375. /**
  4376. * Returns the surface of the Size : width * height (float).
  4377. */
  4378. get: function () {
  4379. return this.width * this.height;
  4380. },
  4381. enumerable: true,
  4382. configurable: true
  4383. });
  4384. /**
  4385. * Returns a new Size set to (0.0, 0.0)
  4386. */
  4387. Size.Zero = function () {
  4388. return new Size(0.0, 0.0);
  4389. };
  4390. /**
  4391. * Returns a new Size set as the addition result of the current Size and the given one.
  4392. */
  4393. Size.prototype.add = function (otherSize) {
  4394. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4395. return r;
  4396. };
  4397. /**
  4398. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4399. */
  4400. Size.prototype.subtract = function (otherSize) {
  4401. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4402. return r;
  4403. };
  4404. /**
  4405. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4406. */
  4407. Size.Lerp = function (start, end, amount) {
  4408. var w = start.width + ((end.width - start.width) * amount);
  4409. var h = start.height + ((end.height - start.height) * amount);
  4410. return new Size(w, h);
  4411. };
  4412. return Size;
  4413. }());
  4414. BABYLON.Size = Size;
  4415. /**
  4416. * Class used to store quaternion data
  4417. * @see https://en.wikipedia.org/wiki/Quaternion
  4418. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4419. */
  4420. var Quaternion = /** @class */ (function () {
  4421. /**
  4422. * Creates a new Quaternion from the given floats
  4423. * @param x defines the first component (0 by default)
  4424. * @param y defines the second component (0 by default)
  4425. * @param z defines the third component (0 by default)
  4426. * @param w defines the fourth component (1.0 by default)
  4427. */
  4428. function Quaternion(
  4429. /** defines the first component (0 by default) */
  4430. x,
  4431. /** defines the second component (0 by default) */
  4432. y,
  4433. /** defines the third component (0 by default) */
  4434. z,
  4435. /** defines the fourth component (1.0 by default) */
  4436. w) {
  4437. if (x === void 0) { x = 0.0; }
  4438. if (y === void 0) { y = 0.0; }
  4439. if (z === void 0) { z = 0.0; }
  4440. if (w === void 0) { w = 1.0; }
  4441. this.x = x;
  4442. this.y = y;
  4443. this.z = z;
  4444. this.w = w;
  4445. }
  4446. /**
  4447. * Gets a string representation for the current quaternion
  4448. * @returns a string with the Quaternion coordinates
  4449. */
  4450. Quaternion.prototype.toString = function () {
  4451. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4452. };
  4453. /**
  4454. * Gets the class name of the quaternion
  4455. * @returns the string "Quaternion"
  4456. */
  4457. Quaternion.prototype.getClassName = function () {
  4458. return "Quaternion";
  4459. };
  4460. /**
  4461. * Gets a hash code for this quaternion
  4462. * @returns the quaternion hash code
  4463. */
  4464. Quaternion.prototype.getHashCode = function () {
  4465. var hash = this.x || 0;
  4466. hash = (hash * 397) ^ (this.y || 0);
  4467. hash = (hash * 397) ^ (this.z || 0);
  4468. hash = (hash * 397) ^ (this.w || 0);
  4469. return hash;
  4470. };
  4471. /**
  4472. * Copy the quaternion to an array
  4473. * @returns a new array populated with 4 elements from the quaternion coordinates
  4474. */
  4475. Quaternion.prototype.asArray = function () {
  4476. return [this.x, this.y, this.z, this.w];
  4477. };
  4478. /**
  4479. * Check if two quaternions are equals
  4480. * @param otherQuaternion defines the second operand
  4481. * @return true if the current quaternion and the given one coordinates are strictly equals
  4482. */
  4483. Quaternion.prototype.equals = function (otherQuaternion) {
  4484. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4485. };
  4486. /**
  4487. * Clone the current quaternion
  4488. * @returns a new quaternion copied from the current one
  4489. */
  4490. Quaternion.prototype.clone = function () {
  4491. return new Quaternion(this.x, this.y, this.z, this.w);
  4492. };
  4493. /**
  4494. * Copy a quaternion to the current one
  4495. * @param other defines the other quaternion
  4496. * @returns the updated current quaternion
  4497. */
  4498. Quaternion.prototype.copyFrom = function (other) {
  4499. this.x = other.x;
  4500. this.y = other.y;
  4501. this.z = other.z;
  4502. this.w = other.w;
  4503. return this;
  4504. };
  4505. /**
  4506. * Updates the current quaternion with the given float coordinates
  4507. * @param x defines the x coordinate
  4508. * @param y defines the y coordinate
  4509. * @param z defines the z coordinate
  4510. * @param w defines the w coordinate
  4511. * @returns the updated current quaternion
  4512. */
  4513. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4514. this.x = x;
  4515. this.y = y;
  4516. this.z = z;
  4517. this.w = w;
  4518. return this;
  4519. };
  4520. /**
  4521. * Updates the current quaternion from the given float coordinates
  4522. * @param x defines the x coordinate
  4523. * @param y defines the y coordinate
  4524. * @param z defines the z coordinate
  4525. * @param w defines the w coordinate
  4526. * @returns the updated current quaternion
  4527. */
  4528. Quaternion.prototype.set = function (x, y, z, w) {
  4529. return this.copyFromFloats(x, y, z, w);
  4530. };
  4531. /**
  4532. * Adds two quaternions
  4533. * @param other defines the second operand
  4534. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4535. */
  4536. Quaternion.prototype.add = function (other) {
  4537. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4538. };
  4539. /**
  4540. * Add a quaternion to the current one
  4541. * @param other defines the quaternion to add
  4542. * @returns the current quaternion
  4543. */
  4544. Quaternion.prototype.addInPlace = function (other) {
  4545. this.x += other.x;
  4546. this.y += other.y;
  4547. this.z += other.z;
  4548. this.w += other.w;
  4549. return this;
  4550. };
  4551. /**
  4552. * Subtract two quaternions
  4553. * @param other defines the second operand
  4554. * @returns a new quaternion as the subtraction result of the given one from the current one
  4555. */
  4556. Quaternion.prototype.subtract = function (other) {
  4557. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4558. };
  4559. /**
  4560. * Multiplies the current quaternion by a scale factor
  4561. * @param value defines the scale factor
  4562. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4563. */
  4564. Quaternion.prototype.scale = function (value) {
  4565. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4566. };
  4567. /**
  4568. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4569. * @param scale defines the scale factor
  4570. * @param result defines the Quaternion object where to store the result
  4571. * @returns the unmodified current quaternion
  4572. */
  4573. Quaternion.prototype.scaleToRef = function (scale, result) {
  4574. result.x = this.x * scale;
  4575. result.y = this.y * scale;
  4576. result.z = this.z * scale;
  4577. result.w = this.w * scale;
  4578. return this;
  4579. };
  4580. /**
  4581. * Multiplies in place the current quaternion by a scale factor
  4582. * @param value defines the scale factor
  4583. * @returns the current modified quaternion
  4584. */
  4585. Quaternion.prototype.scaleInPlace = function (value) {
  4586. this.x *= value;
  4587. this.y *= value;
  4588. this.z *= value;
  4589. this.w *= value;
  4590. return this;
  4591. };
  4592. /**
  4593. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4594. * @param scale defines the scale factor
  4595. * @param result defines the Quaternion object where to store the result
  4596. * @returns the unmodified current quaternion
  4597. */
  4598. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4599. result.x += this.x * scale;
  4600. result.y += this.y * scale;
  4601. result.z += this.z * scale;
  4602. result.w += this.w * scale;
  4603. return this;
  4604. };
  4605. /**
  4606. * Multiplies two quaternions
  4607. * @param q1 defines the second operand
  4608. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4609. */
  4610. Quaternion.prototype.multiply = function (q1) {
  4611. var result = new Quaternion(0, 0, 0, 1.0);
  4612. this.multiplyToRef(q1, result);
  4613. return result;
  4614. };
  4615. /**
  4616. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4617. * @param q1 defines the second operand
  4618. * @param result defines the target quaternion
  4619. * @returns the current quaternion
  4620. */
  4621. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4622. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4623. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4624. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4625. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4626. result.copyFromFloats(x, y, z, w);
  4627. return this;
  4628. };
  4629. /**
  4630. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4631. * @param q1 defines the second operand
  4632. * @returns the currentupdated quaternion
  4633. */
  4634. Quaternion.prototype.multiplyInPlace = function (q1) {
  4635. this.multiplyToRef(q1, this);
  4636. return this;
  4637. };
  4638. /**
  4639. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4640. * @param ref defines the target quaternion
  4641. * @returns the current quaternion
  4642. */
  4643. Quaternion.prototype.conjugateToRef = function (ref) {
  4644. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4645. return this;
  4646. };
  4647. /**
  4648. * Conjugates in place (1-q) the current quaternion
  4649. * @returns the current updated quaternion
  4650. */
  4651. Quaternion.prototype.conjugateInPlace = function () {
  4652. this.x *= -1;
  4653. this.y *= -1;
  4654. this.z *= -1;
  4655. return this;
  4656. };
  4657. /**
  4658. * Conjugates in place (1-q) the current quaternion
  4659. * @returns a new quaternion
  4660. */
  4661. Quaternion.prototype.conjugate = function () {
  4662. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4663. return result;
  4664. };
  4665. /**
  4666. * Gets length of current quaternion
  4667. * @returns the quaternion length (float)
  4668. */
  4669. Quaternion.prototype.length = function () {
  4670. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4671. };
  4672. /**
  4673. * Normalize in place the current quaternion
  4674. * @returns the current updated quaternion
  4675. */
  4676. Quaternion.prototype.normalize = function () {
  4677. var length = 1.0 / this.length();
  4678. this.x *= length;
  4679. this.y *= length;
  4680. this.z *= length;
  4681. this.w *= length;
  4682. return this;
  4683. };
  4684. /**
  4685. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4686. * @param order is a reserved parameter and is ignore for now
  4687. * @returns a new Vector3 containing the Euler angles
  4688. */
  4689. Quaternion.prototype.toEulerAngles = function (order) {
  4690. if (order === void 0) { order = "YZX"; }
  4691. var result = Vector3.Zero();
  4692. this.toEulerAnglesToRef(result, order);
  4693. return result;
  4694. };
  4695. /**
  4696. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4697. * @param result defines the vector which will be filled with the Euler angles
  4698. * @param order is a reserved parameter and is ignore for now
  4699. * @returns the current unchanged quaternion
  4700. */
  4701. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4702. if (order === void 0) { order = "YZX"; }
  4703. var qz = this.z;
  4704. var qx = this.x;
  4705. var qy = this.y;
  4706. var qw = this.w;
  4707. var sqw = qw * qw;
  4708. var sqz = qz * qz;
  4709. var sqx = qx * qx;
  4710. var sqy = qy * qy;
  4711. var zAxisY = qy * qz - qx * qw;
  4712. var limit = .4999999;
  4713. if (zAxisY < -limit) {
  4714. result.y = 2 * Math.atan2(qy, qw);
  4715. result.x = Math.PI / 2;
  4716. result.z = 0;
  4717. }
  4718. else if (zAxisY > limit) {
  4719. result.y = 2 * Math.atan2(qy, qw);
  4720. result.x = -Math.PI / 2;
  4721. result.z = 0;
  4722. }
  4723. else {
  4724. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4725. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4726. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4727. }
  4728. return this;
  4729. };
  4730. /**
  4731. * Updates the given rotation matrix with the current quaternion values
  4732. * @param result defines the target matrix
  4733. * @returns the current unchanged quaternion
  4734. */
  4735. Quaternion.prototype.toRotationMatrix = function (result) {
  4736. var xx = this.x * this.x;
  4737. var yy = this.y * this.y;
  4738. var zz = this.z * this.z;
  4739. var xy = this.x * this.y;
  4740. var zw = this.z * this.w;
  4741. var zx = this.z * this.x;
  4742. var yw = this.y * this.w;
  4743. var yz = this.y * this.z;
  4744. var xw = this.x * this.w;
  4745. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4746. result.m[1] = 2.0 * (xy + zw);
  4747. result.m[2] = 2.0 * (zx - yw);
  4748. result.m[3] = 0;
  4749. result.m[4] = 2.0 * (xy - zw);
  4750. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4751. result.m[6] = 2.0 * (yz + xw);
  4752. result.m[7] = 0;
  4753. result.m[8] = 2.0 * (zx + yw);
  4754. result.m[9] = 2.0 * (yz - xw);
  4755. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4756. result.m[11] = 0;
  4757. result.m[12] = 0;
  4758. result.m[13] = 0;
  4759. result.m[14] = 0;
  4760. result.m[15] = 1.0;
  4761. result._markAsUpdated();
  4762. return this;
  4763. };
  4764. /**
  4765. * Updates the current quaternion from the given rotation matrix values
  4766. * @param matrix defines the source matrix
  4767. * @returns the current updated quaternion
  4768. */
  4769. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4770. Quaternion.FromRotationMatrixToRef(matrix, this);
  4771. return this;
  4772. };
  4773. // Statics
  4774. /**
  4775. * Creates a new quaternion from a rotation matrix
  4776. * @param matrix defines the source matrix
  4777. * @returns a new quaternion created from the given rotation matrix values
  4778. */
  4779. Quaternion.FromRotationMatrix = function (matrix) {
  4780. var result = new Quaternion();
  4781. Quaternion.FromRotationMatrixToRef(matrix, result);
  4782. return result;
  4783. };
  4784. /**
  4785. * Updates the given quaternion with the given rotation matrix values
  4786. * @param matrix defines the source matrix
  4787. * @param result defines the target quaternion
  4788. */
  4789. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4790. var data = matrix.m;
  4791. var m11 = data[0], m12 = data[4], m13 = data[8];
  4792. var m21 = data[1], m22 = data[5], m23 = data[9];
  4793. var m31 = data[2], m32 = data[6], m33 = data[10];
  4794. var trace = m11 + m22 + m33;
  4795. var s;
  4796. if (trace > 0) {
  4797. s = 0.5 / Math.sqrt(trace + 1.0);
  4798. result.w = 0.25 / s;
  4799. result.x = (m32 - m23) * s;
  4800. result.y = (m13 - m31) * s;
  4801. result.z = (m21 - m12) * s;
  4802. }
  4803. else if (m11 > m22 && m11 > m33) {
  4804. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4805. result.w = (m32 - m23) / s;
  4806. result.x = 0.25 * s;
  4807. result.y = (m12 + m21) / s;
  4808. result.z = (m13 + m31) / s;
  4809. }
  4810. else if (m22 > m33) {
  4811. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4812. result.w = (m13 - m31) / s;
  4813. result.x = (m12 + m21) / s;
  4814. result.y = 0.25 * s;
  4815. result.z = (m23 + m32) / s;
  4816. }
  4817. else {
  4818. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4819. result.w = (m21 - m12) / s;
  4820. result.x = (m13 + m31) / s;
  4821. result.y = (m23 + m32) / s;
  4822. result.z = 0.25 * s;
  4823. }
  4824. };
  4825. /**
  4826. * Returns the dot product (float) between the quaternions "left" and "right"
  4827. * @param left defines the left operand
  4828. * @param right defines the right operand
  4829. * @returns the dot product
  4830. */
  4831. Quaternion.Dot = function (left, right) {
  4832. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4833. };
  4834. /**
  4835. * Checks if the two quaternions are close to each other
  4836. * @param quat0 defines the first quaternion to check
  4837. * @param quat1 defines the second quaternion to check
  4838. * @returns true if the two quaternions are close to each other
  4839. */
  4840. Quaternion.AreClose = function (quat0, quat1) {
  4841. var dot = Quaternion.Dot(quat0, quat1);
  4842. return dot >= 0;
  4843. };
  4844. /**
  4845. * Creates an empty quaternion
  4846. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4847. */
  4848. Quaternion.Zero = function () {
  4849. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4850. };
  4851. /**
  4852. * Inverse a given quaternion
  4853. * @param q defines the source quaternion
  4854. * @returns a new quaternion as the inverted current quaternion
  4855. */
  4856. Quaternion.Inverse = function (q) {
  4857. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4858. };
  4859. /**
  4860. * Creates an identity quaternion
  4861. * @returns the identity quaternion
  4862. */
  4863. Quaternion.Identity = function () {
  4864. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4865. };
  4866. /**
  4867. * Gets a boolean indicating if the given quaternion is identity
  4868. * @param quaternion defines the quaternion to check
  4869. * @returns true if the quaternion is identity
  4870. */
  4871. Quaternion.IsIdentity = function (quaternion) {
  4872. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4873. };
  4874. /**
  4875. * Creates a quaternion from a rotation around an axis
  4876. * @param axis defines the axis to use
  4877. * @param angle defines the angle to use
  4878. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4879. */
  4880. Quaternion.RotationAxis = function (axis, angle) {
  4881. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4882. };
  4883. /**
  4884. * Creates a rotation around an axis and stores it into the given quaternion
  4885. * @param axis defines the axis to use
  4886. * @param angle defines the angle to use
  4887. * @param result defines the target quaternion
  4888. * @returns the target quaternion
  4889. */
  4890. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4891. var sin = Math.sin(angle / 2);
  4892. axis.normalize();
  4893. result.w = Math.cos(angle / 2);
  4894. result.x = axis.x * sin;
  4895. result.y = axis.y * sin;
  4896. result.z = axis.z * sin;
  4897. return result;
  4898. };
  4899. /**
  4900. * Creates a new quaternion from data stored into an array
  4901. * @param array defines the data source
  4902. * @param offset defines the offset in the source array where the data starts
  4903. * @returns a new quaternion
  4904. */
  4905. Quaternion.FromArray = function (array, offset) {
  4906. if (!offset) {
  4907. offset = 0;
  4908. }
  4909. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4910. };
  4911. /**
  4912. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4913. * @param yaw defines the rotation around Y axis
  4914. * @param pitch defines the rotation around X axis
  4915. * @param roll defines the rotation around Z axis
  4916. * @returns the new quaternion
  4917. */
  4918. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4919. var q = new Quaternion();
  4920. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4921. return q;
  4922. };
  4923. /**
  4924. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4925. * @param yaw defines the rotation around Y axis
  4926. * @param pitch defines the rotation around X axis
  4927. * @param roll defines the rotation around Z axis
  4928. * @param result defines the target quaternion
  4929. */
  4930. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4931. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4932. var halfRoll = roll * 0.5;
  4933. var halfPitch = pitch * 0.5;
  4934. var halfYaw = yaw * 0.5;
  4935. var sinRoll = Math.sin(halfRoll);
  4936. var cosRoll = Math.cos(halfRoll);
  4937. var sinPitch = Math.sin(halfPitch);
  4938. var cosPitch = Math.cos(halfPitch);
  4939. var sinYaw = Math.sin(halfYaw);
  4940. var cosYaw = Math.cos(halfYaw);
  4941. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4942. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4943. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4944. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4945. };
  4946. /**
  4947. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4948. * @param alpha defines the rotation around first axis
  4949. * @param beta defines the rotation around second axis
  4950. * @param gamma defines the rotation around third axis
  4951. * @returns the new quaternion
  4952. */
  4953. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4954. var result = new Quaternion();
  4955. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4956. return result;
  4957. };
  4958. /**
  4959. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4960. * @param alpha defines the rotation around first axis
  4961. * @param beta defines the rotation around second axis
  4962. * @param gamma defines the rotation around third axis
  4963. * @param result defines the target quaternion
  4964. */
  4965. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4966. // Produces a quaternion from Euler angles in the z-x-z orientation
  4967. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4968. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4969. var halfBeta = beta * 0.5;
  4970. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4971. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4972. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4973. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4974. };
  4975. /**
  4976. * 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)
  4977. * @param axis1 defines the first axis
  4978. * @param axis2 defines the second axis
  4979. * @param axis3 defines the third axis
  4980. * @returns the new quaternion
  4981. */
  4982. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4983. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4984. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4985. return quat;
  4986. };
  4987. /**
  4988. * 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
  4989. * @param axis1 defines the first axis
  4990. * @param axis2 defines the second axis
  4991. * @param axis3 defines the third axis
  4992. * @param ref defines the target quaternion
  4993. */
  4994. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4995. var rotMat = MathTmp.Matrix[0];
  4996. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4997. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4998. };
  4999. /**
  5000. * Interpolates between two quaternions
  5001. * @param left defines first quaternion
  5002. * @param right defines second quaternion
  5003. * @param amount defines the gradient to use
  5004. * @returns the new interpolated quaternion
  5005. */
  5006. Quaternion.Slerp = function (left, right, amount) {
  5007. var result = Quaternion.Identity();
  5008. Quaternion.SlerpToRef(left, right, amount, result);
  5009. return result;
  5010. };
  5011. /**
  5012. * Interpolates between two quaternions and stores it into a target quaternion
  5013. * @param left defines first quaternion
  5014. * @param right defines second quaternion
  5015. * @param amount defines the gradient to use
  5016. * @param result defines the target quaternion
  5017. */
  5018. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5019. var num2;
  5020. var num3;
  5021. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5022. var flag = false;
  5023. if (num4 < 0) {
  5024. flag = true;
  5025. num4 = -num4;
  5026. }
  5027. if (num4 > 0.999999) {
  5028. num3 = 1 - amount;
  5029. num2 = flag ? -amount : amount;
  5030. }
  5031. else {
  5032. var num5 = Math.acos(num4);
  5033. var num6 = (1.0 / Math.sin(num5));
  5034. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5035. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5036. }
  5037. result.x = (num3 * left.x) + (num2 * right.x);
  5038. result.y = (num3 * left.y) + (num2 * right.y);
  5039. result.z = (num3 * left.z) + (num2 * right.z);
  5040. result.w = (num3 * left.w) + (num2 * right.w);
  5041. };
  5042. /**
  5043. * Interpolate between two quaternions using Hermite interpolation
  5044. * @param value1 defines first quaternion
  5045. * @param tangent1 defines the incoming tangent
  5046. * @param value2 defines second quaternion
  5047. * @param tangent2 defines the outgoing tangent
  5048. * @param amount defines the target quaternion
  5049. * @returns the new interpolated quaternion
  5050. */
  5051. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5052. var squared = amount * amount;
  5053. var cubed = amount * squared;
  5054. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5055. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5056. var part3 = (cubed - (2.0 * squared)) + amount;
  5057. var part4 = cubed - squared;
  5058. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5059. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5060. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5061. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5062. return new Quaternion(x, y, z, w);
  5063. };
  5064. return Quaternion;
  5065. }());
  5066. BABYLON.Quaternion = Quaternion;
  5067. /**
  5068. * Class used to store matrix data (4x4)
  5069. */
  5070. var Matrix = /** @class */ (function () {
  5071. /**
  5072. * Creates an empty matrix (filled with zeros)
  5073. */
  5074. function Matrix() {
  5075. this._isIdentity = false;
  5076. this._isIdentityDirty = true;
  5077. /**
  5078. * Gets or sets the internal data of the matrix
  5079. */
  5080. this.m = new Float32Array(16);
  5081. this._markAsUpdated();
  5082. }
  5083. /** @hidden */
  5084. Matrix.prototype._markAsUpdated = function () {
  5085. this.updateFlag = Matrix._updateFlagSeed++;
  5086. this._isIdentityDirty = true;
  5087. };
  5088. // Properties
  5089. /**
  5090. * Check if the current matrix is indentity
  5091. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5092. * @returns true is the matrix is the identity matrix
  5093. */
  5094. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5095. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5096. if (this._isIdentityDirty) {
  5097. this._isIdentityDirty = false;
  5098. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5099. this._isIdentity = false;
  5100. }
  5101. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5102. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5103. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5104. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5105. this._isIdentity = false;
  5106. }
  5107. else {
  5108. this._isIdentity = true;
  5109. }
  5110. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5111. this._isIdentity = false;
  5112. }
  5113. }
  5114. return this._isIdentity;
  5115. };
  5116. /**
  5117. * Gets the determinant of the matrix
  5118. * @returns the matrix determinant
  5119. */
  5120. Matrix.prototype.determinant = function () {
  5121. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5122. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5123. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5124. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5125. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5126. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5127. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5128. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5129. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5130. };
  5131. // Methods
  5132. /**
  5133. * Returns the matrix as a Float32Array
  5134. * @returns the matrix underlying array
  5135. */
  5136. Matrix.prototype.toArray = function () {
  5137. return this.m;
  5138. };
  5139. /**
  5140. * Returns the matrix as a Float32Array
  5141. * @returns the matrix underlying array.
  5142. */
  5143. Matrix.prototype.asArray = function () {
  5144. return this.toArray();
  5145. };
  5146. /**
  5147. * Inverts the current matrix in place
  5148. * @returns the current inverted matrix
  5149. */
  5150. Matrix.prototype.invert = function () {
  5151. this.invertToRef(this);
  5152. return this;
  5153. };
  5154. /**
  5155. * Sets all the matrix elements to zero
  5156. * @returns the current matrix
  5157. */
  5158. Matrix.prototype.reset = function () {
  5159. for (var index = 0; index < 16; index++) {
  5160. this.m[index] = 0.0;
  5161. }
  5162. this._markAsUpdated();
  5163. return this;
  5164. };
  5165. /**
  5166. * Adds the current matrix with a second one
  5167. * @param other defines the matrix to add
  5168. * @returns a new matrix as the addition of the current matrix and the given one
  5169. */
  5170. Matrix.prototype.add = function (other) {
  5171. var result = new Matrix();
  5172. this.addToRef(other, result);
  5173. return result;
  5174. };
  5175. /**
  5176. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5177. * @param other defines the matrix to add
  5178. * @param result defines the target matrix
  5179. * @returns the current matrix
  5180. */
  5181. Matrix.prototype.addToRef = function (other, result) {
  5182. for (var index = 0; index < 16; index++) {
  5183. result.m[index] = this.m[index] + other.m[index];
  5184. }
  5185. result._markAsUpdated();
  5186. return this;
  5187. };
  5188. /**
  5189. * Adds in place the given matrix to the current matrix
  5190. * @param other defines the second operand
  5191. * @returns the current updated matrix
  5192. */
  5193. Matrix.prototype.addToSelf = function (other) {
  5194. for (var index = 0; index < 16; index++) {
  5195. this.m[index] += other.m[index];
  5196. }
  5197. this._markAsUpdated();
  5198. return this;
  5199. };
  5200. /**
  5201. * Sets the given matrix to the current inverted Matrix
  5202. * @param other defines the target matrix
  5203. * @returns the unmodified current matrix
  5204. */
  5205. Matrix.prototype.invertToRef = function (other) {
  5206. var l1 = this.m[0];
  5207. var l2 = this.m[1];
  5208. var l3 = this.m[2];
  5209. var l4 = this.m[3];
  5210. var l5 = this.m[4];
  5211. var l6 = this.m[5];
  5212. var l7 = this.m[6];
  5213. var l8 = this.m[7];
  5214. var l9 = this.m[8];
  5215. var l10 = this.m[9];
  5216. var l11 = this.m[10];
  5217. var l12 = this.m[11];
  5218. var l13 = this.m[12];
  5219. var l14 = this.m[13];
  5220. var l15 = this.m[14];
  5221. var l16 = this.m[15];
  5222. var l17 = (l11 * l16) - (l12 * l15);
  5223. var l18 = (l10 * l16) - (l12 * l14);
  5224. var l19 = (l10 * l15) - (l11 * l14);
  5225. var l20 = (l9 * l16) - (l12 * l13);
  5226. var l21 = (l9 * l15) - (l11 * l13);
  5227. var l22 = (l9 * l14) - (l10 * l13);
  5228. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5229. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5230. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5231. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5232. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5233. var l28 = (l7 * l16) - (l8 * l15);
  5234. var l29 = (l6 * l16) - (l8 * l14);
  5235. var l30 = (l6 * l15) - (l7 * l14);
  5236. var l31 = (l5 * l16) - (l8 * l13);
  5237. var l32 = (l5 * l15) - (l7 * l13);
  5238. var l33 = (l5 * l14) - (l6 * l13);
  5239. var l34 = (l7 * l12) - (l8 * l11);
  5240. var l35 = (l6 * l12) - (l8 * l10);
  5241. var l36 = (l6 * l11) - (l7 * l10);
  5242. var l37 = (l5 * l12) - (l8 * l9);
  5243. var l38 = (l5 * l11) - (l7 * l9);
  5244. var l39 = (l5 * l10) - (l6 * l9);
  5245. other.m[0] = l23 * l27;
  5246. other.m[4] = l24 * l27;
  5247. other.m[8] = l25 * l27;
  5248. other.m[12] = l26 * l27;
  5249. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5250. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5251. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5252. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5253. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5254. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5255. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5256. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5257. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5258. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5259. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5260. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5261. other._markAsUpdated();
  5262. return this;
  5263. };
  5264. /**
  5265. * Inserts the translation vector (using 3 floats) in the current matrix
  5266. * @param x defines the 1st component of the translation
  5267. * @param y defines the 2nd component of the translation
  5268. * @param z defines the 3rd component of the translation
  5269. * @returns the current updated matrix
  5270. */
  5271. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5272. this.m[12] = x;
  5273. this.m[13] = y;
  5274. this.m[14] = z;
  5275. this._markAsUpdated();
  5276. return this;
  5277. };
  5278. /**
  5279. * Inserts the translation vector in the current matrix
  5280. * @param vector3 defines the translation to insert
  5281. * @returns the current updated matrix
  5282. */
  5283. Matrix.prototype.setTranslation = function (vector3) {
  5284. this.m[12] = vector3.x;
  5285. this.m[13] = vector3.y;
  5286. this.m[14] = vector3.z;
  5287. this._markAsUpdated();
  5288. return this;
  5289. };
  5290. /**
  5291. * Gets the translation value of the current matrix
  5292. * @returns a new Vector3 as the extracted translation from the matrix
  5293. */
  5294. Matrix.prototype.getTranslation = function () {
  5295. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5296. };
  5297. /**
  5298. * Fill a Vector3 with the extracted translation from the matrix
  5299. * @param result defines the Vector3 where to store the translation
  5300. * @returns the current matrix
  5301. */
  5302. Matrix.prototype.getTranslationToRef = function (result) {
  5303. result.x = this.m[12];
  5304. result.y = this.m[13];
  5305. result.z = this.m[14];
  5306. return this;
  5307. };
  5308. /**
  5309. * Remove rotation and scaling part from the matrix
  5310. * @returns the updated matrix
  5311. */
  5312. Matrix.prototype.removeRotationAndScaling = function () {
  5313. this.setRowFromFloats(0, 1, 0, 0, 0);
  5314. this.setRowFromFloats(1, 0, 1, 0, 0);
  5315. this.setRowFromFloats(2, 0, 0, 1, 0);
  5316. return this;
  5317. };
  5318. /**
  5319. * Multiply two matrices
  5320. * @param other defines the second operand
  5321. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5322. */
  5323. Matrix.prototype.multiply = function (other) {
  5324. var result = new Matrix();
  5325. this.multiplyToRef(other, result);
  5326. return result;
  5327. };
  5328. /**
  5329. * Copy the current matrix from the given one
  5330. * @param other defines the source matrix
  5331. * @returns the current updated matrix
  5332. */
  5333. Matrix.prototype.copyFrom = function (other) {
  5334. for (var index = 0; index < 16; index++) {
  5335. this.m[index] = other.m[index];
  5336. }
  5337. this._markAsUpdated();
  5338. return this;
  5339. };
  5340. /**
  5341. * Populates the given array from the starting index with the current matrix values
  5342. * @param array defines the target array
  5343. * @param offset defines the offset in the target array where to start storing values
  5344. * @returns the current matrix
  5345. */
  5346. Matrix.prototype.copyToArray = function (array, offset) {
  5347. if (offset === void 0) { offset = 0; }
  5348. for (var index = 0; index < 16; index++) {
  5349. array[offset + index] = this.m[index];
  5350. }
  5351. return this;
  5352. };
  5353. /**
  5354. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5355. * @param other defines the second operand
  5356. * @param result defines the matrix where to store the multiplication
  5357. * @returns the current matrix
  5358. */
  5359. Matrix.prototype.multiplyToRef = function (other, result) {
  5360. this.multiplyToArray(other, result.m, 0);
  5361. result._markAsUpdated();
  5362. return this;
  5363. };
  5364. /**
  5365. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5366. * @param other defines the second operand
  5367. * @param result defines the array where to store the multiplication
  5368. * @param offset defines the offset in the target array where to start storing values
  5369. * @returns the current matrix
  5370. */
  5371. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5372. var tm0 = this.m[0];
  5373. var tm1 = this.m[1];
  5374. var tm2 = this.m[2];
  5375. var tm3 = this.m[3];
  5376. var tm4 = this.m[4];
  5377. var tm5 = this.m[5];
  5378. var tm6 = this.m[6];
  5379. var tm7 = this.m[7];
  5380. var tm8 = this.m[8];
  5381. var tm9 = this.m[9];
  5382. var tm10 = this.m[10];
  5383. var tm11 = this.m[11];
  5384. var tm12 = this.m[12];
  5385. var tm13 = this.m[13];
  5386. var tm14 = this.m[14];
  5387. var tm15 = this.m[15];
  5388. var om0 = other.m[0];
  5389. var om1 = other.m[1];
  5390. var om2 = other.m[2];
  5391. var om3 = other.m[3];
  5392. var om4 = other.m[4];
  5393. var om5 = other.m[5];
  5394. var om6 = other.m[6];
  5395. var om7 = other.m[7];
  5396. var om8 = other.m[8];
  5397. var om9 = other.m[9];
  5398. var om10 = other.m[10];
  5399. var om11 = other.m[11];
  5400. var om12 = other.m[12];
  5401. var om13 = other.m[13];
  5402. var om14 = other.m[14];
  5403. var om15 = other.m[15];
  5404. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5405. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5406. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5407. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5408. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5409. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5410. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5411. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5412. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5413. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5414. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5415. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5416. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5417. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5418. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5419. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5420. return this;
  5421. };
  5422. /**
  5423. * Check equality between this matrix and a second one
  5424. * @param value defines the second matrix to compare
  5425. * @returns true is the current matrix and the given one values are strictly equal
  5426. */
  5427. Matrix.prototype.equals = function (value) {
  5428. return value &&
  5429. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5430. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5431. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5432. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5433. };
  5434. /**
  5435. * Clone the current matrix
  5436. * @returns a new matrix from the current matrix
  5437. */
  5438. Matrix.prototype.clone = function () {
  5439. 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]);
  5440. };
  5441. /**
  5442. * Returns the name of the current matrix class
  5443. * @returns the string "Matrix"
  5444. */
  5445. Matrix.prototype.getClassName = function () {
  5446. return "Matrix";
  5447. };
  5448. /**
  5449. * Gets the hash code of the current matrix
  5450. * @returns the hash code
  5451. */
  5452. Matrix.prototype.getHashCode = function () {
  5453. var hash = this.m[0] || 0;
  5454. for (var i = 1; i < 16; i++) {
  5455. hash = (hash * 397) ^ (this.m[i] || 0);
  5456. }
  5457. return hash;
  5458. };
  5459. /**
  5460. * Decomposes the current Matrix into a translation, rotation and scaling components
  5461. * @param scale defines the scale vector3 given as a reference to update
  5462. * @param rotation defines the rotation quaternion given as a reference to update
  5463. * @param translation defines the translation vector3 given as a reference to update
  5464. * @returns true if operation was successful
  5465. */
  5466. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5467. if (translation) {
  5468. translation.x = this.m[12];
  5469. translation.y = this.m[13];
  5470. translation.z = this.m[14];
  5471. }
  5472. scale = scale || MathTmp.Vector3[0];
  5473. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5474. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5475. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5476. if (this.determinant() <= 0) {
  5477. scale.y *= -1;
  5478. }
  5479. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5480. if (rotation) {
  5481. rotation.x = 0;
  5482. rotation.y = 0;
  5483. rotation.z = 0;
  5484. rotation.w = 1;
  5485. }
  5486. return false;
  5487. }
  5488. if (rotation) {
  5489. 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]);
  5490. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5491. }
  5492. return true;
  5493. };
  5494. /**
  5495. * Gets specific row of the matrix
  5496. * @param index defines the number of the row to get
  5497. * @returns the index-th row of the current matrix as a new Vector4
  5498. */
  5499. Matrix.prototype.getRow = function (index) {
  5500. if (index < 0 || index > 3) {
  5501. return null;
  5502. }
  5503. var i = index * 4;
  5504. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5505. };
  5506. /**
  5507. * Sets the index-th row of the current matrix to the vector4 values
  5508. * @param index defines the number of the row to set
  5509. * @param row defines the target vector4
  5510. * @returns the updated current matrix
  5511. */
  5512. Matrix.prototype.setRow = function (index, row) {
  5513. if (index < 0 || index > 3) {
  5514. return this;
  5515. }
  5516. var i = index * 4;
  5517. this.m[i + 0] = row.x;
  5518. this.m[i + 1] = row.y;
  5519. this.m[i + 2] = row.z;
  5520. this.m[i + 3] = row.w;
  5521. this._markAsUpdated();
  5522. return this;
  5523. };
  5524. /**
  5525. * Compute the transpose of the matrix
  5526. * @returns the new transposed matrix
  5527. */
  5528. Matrix.prototype.transpose = function () {
  5529. return Matrix.Transpose(this);
  5530. };
  5531. /**
  5532. * Compute the transpose of the matrix and store it in a given matrix
  5533. * @param result defines the target matrix
  5534. * @returns the current matrix
  5535. */
  5536. Matrix.prototype.transposeToRef = function (result) {
  5537. Matrix.TransposeToRef(this, result);
  5538. return this;
  5539. };
  5540. /**
  5541. * Sets the index-th row of the current matrix with the given 4 x float values
  5542. * @param index defines the row index
  5543. * @param x defines the x component to set
  5544. * @param y defines the y component to set
  5545. * @param z defines the z component to set
  5546. * @param w defines the w component to set
  5547. * @returns the updated current matrix
  5548. */
  5549. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5550. if (index < 0 || index > 3) {
  5551. return this;
  5552. }
  5553. var i = index * 4;
  5554. this.m[i + 0] = x;
  5555. this.m[i + 1] = y;
  5556. this.m[i + 2] = z;
  5557. this.m[i + 3] = w;
  5558. this._markAsUpdated();
  5559. return this;
  5560. };
  5561. /**
  5562. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5563. * @param scale defines the scale factor
  5564. * @returns a new matrix
  5565. */
  5566. Matrix.prototype.scale = function (scale) {
  5567. var result = new Matrix();
  5568. this.scaleToRef(scale, result);
  5569. return result;
  5570. };
  5571. /**
  5572. * Scale the current matrix values by a factor to a given result matrix
  5573. * @param scale defines the scale factor
  5574. * @param result defines the matrix to store the result
  5575. * @returns the current matrix
  5576. */
  5577. Matrix.prototype.scaleToRef = function (scale, result) {
  5578. for (var index = 0; index < 16; index++) {
  5579. result.m[index] = this.m[index] * scale;
  5580. }
  5581. result._markAsUpdated();
  5582. return this;
  5583. };
  5584. /**
  5585. * Scale the current matrix values by a factor and add the result to a given matrix
  5586. * @param scale defines the scale factor
  5587. * @param result defines the Matrix to store the result
  5588. * @returns the current matrix
  5589. */
  5590. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5591. for (var index = 0; index < 16; index++) {
  5592. result.m[index] += this.m[index] * scale;
  5593. }
  5594. result._markAsUpdated();
  5595. return this;
  5596. };
  5597. /**
  5598. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5599. * @param ref matrix to store the result
  5600. */
  5601. Matrix.prototype.toNormalMatrix = function (ref) {
  5602. this.invertToRef(ref);
  5603. ref.transpose();
  5604. var m = ref.m;
  5605. 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);
  5606. };
  5607. /**
  5608. * Gets only rotation part of the current matrix
  5609. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5610. */
  5611. Matrix.prototype.getRotationMatrix = function () {
  5612. var result = Matrix.Identity();
  5613. this.getRotationMatrixToRef(result);
  5614. return result;
  5615. };
  5616. /**
  5617. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5618. * @param result defines the target matrix to store data to
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5622. var m = this.m;
  5623. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5624. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5625. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5626. if (this.determinant() <= 0) {
  5627. sy *= -1;
  5628. }
  5629. if (sx === 0 || sy === 0 || sz === 0) {
  5630. Matrix.IdentityToRef(result);
  5631. }
  5632. else {
  5633. 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);
  5634. }
  5635. return this;
  5636. };
  5637. // Statics
  5638. /**
  5639. * Creates a matrix from an array
  5640. * @param array defines the source array
  5641. * @param offset defines an offset in the source array
  5642. * @returns a new Matrix set from the starting index of the given array
  5643. */
  5644. Matrix.FromArray = function (array, offset) {
  5645. var result = new Matrix();
  5646. if (!offset) {
  5647. offset = 0;
  5648. }
  5649. Matrix.FromArrayToRef(array, offset, result);
  5650. return result;
  5651. };
  5652. /**
  5653. * Copy the content of an array into a given matrix
  5654. * @param array defines the source array
  5655. * @param offset defines an offset in the source array
  5656. * @param result defines the target matrix
  5657. */
  5658. Matrix.FromArrayToRef = function (array, offset, result) {
  5659. for (var index = 0; index < 16; index++) {
  5660. result.m[index] = array[index + offset];
  5661. }
  5662. result._markAsUpdated();
  5663. };
  5664. /**
  5665. * Stores an array into a matrix after having multiplied each component by a given factor
  5666. * @param array defines the source array
  5667. * @param offset defines the offset in the source array
  5668. * @param scale defines the scaling factor
  5669. * @param result defines the target matrix
  5670. */
  5671. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5672. for (var index = 0; index < 16; index++) {
  5673. result.m[index] = array[index + offset] * scale;
  5674. }
  5675. result._markAsUpdated();
  5676. };
  5677. /**
  5678. * Stores a list of values (16) inside a given matrix
  5679. * @param initialM11 defines 1st value of 1st row
  5680. * @param initialM12 defines 2nd value of 1st row
  5681. * @param initialM13 defines 3rd value of 1st row
  5682. * @param initialM14 defines 4th value of 1st row
  5683. * @param initialM21 defines 1st value of 2nd row
  5684. * @param initialM22 defines 2nd value of 2nd row
  5685. * @param initialM23 defines 3rd value of 2nd row
  5686. * @param initialM24 defines 4th value of 2nd row
  5687. * @param initialM31 defines 1st value of 3rd row
  5688. * @param initialM32 defines 2nd value of 3rd row
  5689. * @param initialM33 defines 3rd value of 3rd row
  5690. * @param initialM34 defines 4th value of 3rd row
  5691. * @param initialM41 defines 1st value of 4th row
  5692. * @param initialM42 defines 2nd value of 4th row
  5693. * @param initialM43 defines 3rd value of 4th row
  5694. * @param initialM44 defines 4th value of 4th row
  5695. * @param result defines the target matrix
  5696. */
  5697. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5698. result.m[0] = initialM11;
  5699. result.m[1] = initialM12;
  5700. result.m[2] = initialM13;
  5701. result.m[3] = initialM14;
  5702. result.m[4] = initialM21;
  5703. result.m[5] = initialM22;
  5704. result.m[6] = initialM23;
  5705. result.m[7] = initialM24;
  5706. result.m[8] = initialM31;
  5707. result.m[9] = initialM32;
  5708. result.m[10] = initialM33;
  5709. result.m[11] = initialM34;
  5710. result.m[12] = initialM41;
  5711. result.m[13] = initialM42;
  5712. result.m[14] = initialM43;
  5713. result.m[15] = initialM44;
  5714. result._markAsUpdated();
  5715. };
  5716. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5717. /**
  5718. * Gets an identity matrix that must not be updated
  5719. */
  5720. get: function () {
  5721. return Matrix._identityReadOnly;
  5722. },
  5723. enumerable: true,
  5724. configurable: true
  5725. });
  5726. /**
  5727. * Creates new matrix from a list of values (16)
  5728. * @param initialM11 defines 1st value of 1st row
  5729. * @param initialM12 defines 2nd value of 1st row
  5730. * @param initialM13 defines 3rd value of 1st row
  5731. * @param initialM14 defines 4th value of 1st row
  5732. * @param initialM21 defines 1st value of 2nd row
  5733. * @param initialM22 defines 2nd value of 2nd row
  5734. * @param initialM23 defines 3rd value of 2nd row
  5735. * @param initialM24 defines 4th value of 2nd row
  5736. * @param initialM31 defines 1st value of 3rd row
  5737. * @param initialM32 defines 2nd value of 3rd row
  5738. * @param initialM33 defines 3rd value of 3rd row
  5739. * @param initialM34 defines 4th value of 3rd row
  5740. * @param initialM41 defines 1st value of 4th row
  5741. * @param initialM42 defines 2nd value of 4th row
  5742. * @param initialM43 defines 3rd value of 4th row
  5743. * @param initialM44 defines 4th value of 4th row
  5744. * @returns the new matrix
  5745. */
  5746. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5747. var result = new Matrix();
  5748. result.m[0] = initialM11;
  5749. result.m[1] = initialM12;
  5750. result.m[2] = initialM13;
  5751. result.m[3] = initialM14;
  5752. result.m[4] = initialM21;
  5753. result.m[5] = initialM22;
  5754. result.m[6] = initialM23;
  5755. result.m[7] = initialM24;
  5756. result.m[8] = initialM31;
  5757. result.m[9] = initialM32;
  5758. result.m[10] = initialM33;
  5759. result.m[11] = initialM34;
  5760. result.m[12] = initialM41;
  5761. result.m[13] = initialM42;
  5762. result.m[14] = initialM43;
  5763. result.m[15] = initialM44;
  5764. return result;
  5765. };
  5766. /**
  5767. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5768. * @param scale defines the scale vector3
  5769. * @param rotation defines the rotation quaternion
  5770. * @param translation defines the translation vector3
  5771. * @returns a new matrix
  5772. */
  5773. Matrix.Compose = function (scale, rotation, translation) {
  5774. var result = Matrix.Identity();
  5775. Matrix.ComposeToRef(scale, rotation, translation, result);
  5776. return result;
  5777. };
  5778. /**
  5779. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5780. * @param scale defines the scale vector3
  5781. * @param rotation defines the rotation quaternion
  5782. * @param translation defines the translation vector3
  5783. * @param result defines the target matrix
  5784. */
  5785. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5786. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5787. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5788. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5789. result.setTranslation(translation);
  5790. };
  5791. /**
  5792. * Creates a new identity matrix
  5793. * @returns a new identity matrix
  5794. */
  5795. Matrix.Identity = function () {
  5796. 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);
  5797. };
  5798. /**
  5799. * Creates a new identity matrix and stores the result in a given matrix
  5800. * @param result defines the target matrix
  5801. */
  5802. Matrix.IdentityToRef = function (result) {
  5803. 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);
  5804. };
  5805. /**
  5806. * Creates a new zero matrix
  5807. * @returns a new zero matrix
  5808. */
  5809. Matrix.Zero = function () {
  5810. 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);
  5811. };
  5812. /**
  5813. * Creates a new rotation matrix for "angle" radians around the X axis
  5814. * @param angle defines the angle (in radians) to use
  5815. * @return the new matrix
  5816. */
  5817. Matrix.RotationX = function (angle) {
  5818. var result = new Matrix();
  5819. Matrix.RotationXToRef(angle, result);
  5820. return result;
  5821. };
  5822. /**
  5823. * Creates a new matrix as the invert of a given matrix
  5824. * @param source defines the source matrix
  5825. * @returns the new matrix
  5826. */
  5827. Matrix.Invert = function (source) {
  5828. var result = new Matrix();
  5829. source.invertToRef(result);
  5830. return result;
  5831. };
  5832. /**
  5833. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5834. * @param angle defines the angle (in radians) to use
  5835. * @param result defines the target matrix
  5836. */
  5837. Matrix.RotationXToRef = function (angle, result) {
  5838. var s = Math.sin(angle);
  5839. var c = Math.cos(angle);
  5840. result.m[0] = 1.0;
  5841. result.m[15] = 1.0;
  5842. result.m[5] = c;
  5843. result.m[10] = c;
  5844. result.m[9] = -s;
  5845. result.m[6] = s;
  5846. result.m[1] = 0.0;
  5847. result.m[2] = 0.0;
  5848. result.m[3] = 0.0;
  5849. result.m[4] = 0.0;
  5850. result.m[7] = 0.0;
  5851. result.m[8] = 0.0;
  5852. result.m[11] = 0.0;
  5853. result.m[12] = 0.0;
  5854. result.m[13] = 0.0;
  5855. result.m[14] = 0.0;
  5856. result._markAsUpdated();
  5857. };
  5858. /**
  5859. * Creates a new rotation matrix for "angle" radians around the Y axis
  5860. * @param angle defines the angle (in radians) to use
  5861. * @return the new matrix
  5862. */
  5863. Matrix.RotationY = function (angle) {
  5864. var result = new Matrix();
  5865. Matrix.RotationYToRef(angle, result);
  5866. return result;
  5867. };
  5868. /**
  5869. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5870. * @param angle defines the angle (in radians) to use
  5871. * @param result defines the target matrix
  5872. */
  5873. Matrix.RotationYToRef = function (angle, result) {
  5874. var s = Math.sin(angle);
  5875. var c = Math.cos(angle);
  5876. result.m[5] = 1.0;
  5877. result.m[15] = 1.0;
  5878. result.m[0] = c;
  5879. result.m[2] = -s;
  5880. result.m[8] = s;
  5881. result.m[10] = c;
  5882. result.m[1] = 0.0;
  5883. result.m[3] = 0.0;
  5884. result.m[4] = 0.0;
  5885. result.m[6] = 0.0;
  5886. result.m[7] = 0.0;
  5887. result.m[9] = 0.0;
  5888. result.m[11] = 0.0;
  5889. result.m[12] = 0.0;
  5890. result.m[13] = 0.0;
  5891. result.m[14] = 0.0;
  5892. result._markAsUpdated();
  5893. };
  5894. /**
  5895. * Creates a new rotation matrix for "angle" radians around the Z axis
  5896. * @param angle defines the angle (in radians) to use
  5897. * @return the new matrix
  5898. */
  5899. Matrix.RotationZ = function (angle) {
  5900. var result = new Matrix();
  5901. Matrix.RotationZToRef(angle, result);
  5902. return result;
  5903. };
  5904. /**
  5905. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5906. * @param angle defines the angle (in radians) to use
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationZToRef = function (angle, result) {
  5910. var s = Math.sin(angle);
  5911. var c = Math.cos(angle);
  5912. result.m[10] = 1.0;
  5913. result.m[15] = 1.0;
  5914. result.m[0] = c;
  5915. result.m[1] = s;
  5916. result.m[4] = -s;
  5917. result.m[5] = c;
  5918. result.m[2] = 0.0;
  5919. result.m[3] = 0.0;
  5920. result.m[6] = 0.0;
  5921. result.m[7] = 0.0;
  5922. result.m[8] = 0.0;
  5923. result.m[9] = 0.0;
  5924. result.m[11] = 0.0;
  5925. result.m[12] = 0.0;
  5926. result.m[13] = 0.0;
  5927. result.m[14] = 0.0;
  5928. result._markAsUpdated();
  5929. };
  5930. /**
  5931. * Creates a new rotation matrix for "angle" radians around the given axis
  5932. * @param axis defines the axis to use
  5933. * @param angle defines the angle (in radians) to use
  5934. * @return the new matrix
  5935. */
  5936. Matrix.RotationAxis = function (axis, angle) {
  5937. var result = Matrix.Zero();
  5938. Matrix.RotationAxisToRef(axis, angle, result);
  5939. return result;
  5940. };
  5941. /**
  5942. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5943. * @param axis defines the axis to use
  5944. * @param angle defines the angle (in radians) to use
  5945. * @param result defines the target matrix
  5946. */
  5947. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5948. var s = Math.sin(-angle);
  5949. var c = Math.cos(-angle);
  5950. var c1 = 1 - c;
  5951. axis.normalize();
  5952. result.m[0] = (axis.x * axis.x) * c1 + c;
  5953. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5954. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5955. result.m[3] = 0.0;
  5956. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5957. result.m[5] = (axis.y * axis.y) * c1 + c;
  5958. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5959. result.m[7] = 0.0;
  5960. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5961. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5962. result.m[10] = (axis.z * axis.z) * c1 + c;
  5963. result.m[11] = 0.0;
  5964. result.m[15] = 1.0;
  5965. result._markAsUpdated();
  5966. };
  5967. /**
  5968. * Creates a rotation matrix
  5969. * @param yaw defines the yaw angle in radians (Y axis)
  5970. * @param pitch defines the pitch angle in radians (X axis)
  5971. * @param roll defines the roll angle in radians (X axis)
  5972. * @returns the new rotation matrix
  5973. */
  5974. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5975. var result = new Matrix();
  5976. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5977. return result;
  5978. };
  5979. /**
  5980. * Creates a rotation matrix and stores it in a given matrix
  5981. * @param yaw defines the yaw angle in radians (Y axis)
  5982. * @param pitch defines the pitch angle in radians (X axis)
  5983. * @param roll defines the roll angle in radians (X axis)
  5984. * @param result defines the target matrix
  5985. */
  5986. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5987. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5988. this._tempQuaternion.toRotationMatrix(result);
  5989. };
  5990. /**
  5991. * Creates a scaling matrix
  5992. * @param x defines the scale factor on X axis
  5993. * @param y defines the scale factor on Y axis
  5994. * @param z defines the scale factor on Z axis
  5995. * @returns the new matrix
  5996. */
  5997. Matrix.Scaling = function (x, y, z) {
  5998. var result = Matrix.Zero();
  5999. Matrix.ScalingToRef(x, y, z, result);
  6000. return result;
  6001. };
  6002. /**
  6003. * Creates a scaling matrix and stores it in a given matrix
  6004. * @param x defines the scale factor on X axis
  6005. * @param y defines the scale factor on Y axis
  6006. * @param z defines the scale factor on Z axis
  6007. * @param result defines the target matrix
  6008. */
  6009. Matrix.ScalingToRef = function (x, y, z, result) {
  6010. result.m[0] = x;
  6011. result.m[1] = 0.0;
  6012. result.m[2] = 0.0;
  6013. result.m[3] = 0.0;
  6014. result.m[4] = 0.0;
  6015. result.m[5] = y;
  6016. result.m[6] = 0.0;
  6017. result.m[7] = 0.0;
  6018. result.m[8] = 0.0;
  6019. result.m[9] = 0.0;
  6020. result.m[10] = z;
  6021. result.m[11] = 0.0;
  6022. result.m[12] = 0.0;
  6023. result.m[13] = 0.0;
  6024. result.m[14] = 0.0;
  6025. result.m[15] = 1.0;
  6026. result._markAsUpdated();
  6027. };
  6028. /**
  6029. * Creates a translation matrix
  6030. * @param x defines the translation on X axis
  6031. * @param y defines the translation on Y axis
  6032. * @param z defines the translationon Z axis
  6033. * @returns the new matrix
  6034. */
  6035. Matrix.Translation = function (x, y, z) {
  6036. var result = Matrix.Identity();
  6037. Matrix.TranslationToRef(x, y, z, result);
  6038. return result;
  6039. };
  6040. /**
  6041. * Creates a translation matrix and stores it in a given matrix
  6042. * @param x defines the translation on X axis
  6043. * @param y defines the translation on Y axis
  6044. * @param z defines the translationon Z axis
  6045. * @param result defines the target matrix
  6046. */
  6047. Matrix.TranslationToRef = function (x, y, z, result) {
  6048. 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);
  6049. };
  6050. /**
  6051. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6052. * @param startValue defines the start value
  6053. * @param endValue defines the end value
  6054. * @param gradient defines the gradient factor
  6055. * @returns the new matrix
  6056. */
  6057. Matrix.Lerp = function (startValue, endValue, gradient) {
  6058. var result = Matrix.Zero();
  6059. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6060. return result;
  6061. };
  6062. /**
  6063. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6064. * @param startValue defines the start value
  6065. * @param endValue defines the end value
  6066. * @param gradient defines the gradient factor
  6067. * @param result defines the Matrix object where to store data
  6068. */
  6069. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6070. for (var index = 0; index < 16; index++) {
  6071. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6072. }
  6073. result._markAsUpdated();
  6074. };
  6075. /**
  6076. * Builds a new matrix whose values are computed by:
  6077. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6078. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6079. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6080. * @param startValue defines the first matrix
  6081. * @param endValue defines the second matrix
  6082. * @param gradient defines the gradient between the two matrices
  6083. * @returns the new matrix
  6084. */
  6085. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6086. var result = Matrix.Zero();
  6087. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6088. return result;
  6089. };
  6090. /**
  6091. * Update a matrix to values which are computed by:
  6092. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6093. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6094. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6095. * @param startValue defines the first matrix
  6096. * @param endValue defines the second matrix
  6097. * @param gradient defines the gradient between the two matrices
  6098. * @param result defines the target matrix
  6099. */
  6100. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6101. var startScale = MathTmp.Vector3[0];
  6102. var startRotation = MathTmp.Quaternion[0];
  6103. var startTranslation = MathTmp.Vector3[1];
  6104. startValue.decompose(startScale, startRotation, startTranslation);
  6105. var endScale = MathTmp.Vector3[2];
  6106. var endRotation = MathTmp.Quaternion[1];
  6107. var endTranslation = MathTmp.Vector3[3];
  6108. endValue.decompose(endScale, endRotation, endTranslation);
  6109. var resultScale = MathTmp.Vector3[4];
  6110. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6111. var resultRotation = MathTmp.Quaternion[2];
  6112. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6113. var resultTranslation = MathTmp.Vector3[5];
  6114. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6115. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6116. };
  6117. /**
  6118. * 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"
  6119. * This function works in left handed mode
  6120. * @param eye defines the final position of the entity
  6121. * @param target defines where the entity should look at
  6122. * @param up defines the up vector for the entity
  6123. * @returns the new matrix
  6124. */
  6125. Matrix.LookAtLH = function (eye, target, up) {
  6126. var result = Matrix.Zero();
  6127. Matrix.LookAtLHToRef(eye, target, up, result);
  6128. return result;
  6129. };
  6130. /**
  6131. * 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".
  6132. * This function works in left handed mode
  6133. * @param eye defines the final position of the entity
  6134. * @param target defines where the entity should look at
  6135. * @param up defines the up vector for the entity
  6136. * @param result defines the target matrix
  6137. */
  6138. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6139. // Z axis
  6140. target.subtractToRef(eye, this._zAxis);
  6141. this._zAxis.normalize();
  6142. // X axis
  6143. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6144. if (this._xAxis.lengthSquared() === 0) {
  6145. this._xAxis.x = 1.0;
  6146. }
  6147. else {
  6148. this._xAxis.normalize();
  6149. }
  6150. // Y axis
  6151. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6152. this._yAxis.normalize();
  6153. // Eye angles
  6154. var ex = -Vector3.Dot(this._xAxis, eye);
  6155. var ey = -Vector3.Dot(this._yAxis, eye);
  6156. var ez = -Vector3.Dot(this._zAxis, eye);
  6157. 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);
  6158. };
  6159. /**
  6160. * 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"
  6161. * This function works in right handed mode
  6162. * @param eye defines the final position of the entity
  6163. * @param target defines where the entity should look at
  6164. * @param up defines the up vector for the entity
  6165. * @returns the new matrix
  6166. */
  6167. Matrix.LookAtRH = function (eye, target, up) {
  6168. var result = Matrix.Zero();
  6169. Matrix.LookAtRHToRef(eye, target, up, result);
  6170. return result;
  6171. };
  6172. /**
  6173. * 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".
  6174. * This function works in right handed mode
  6175. * @param eye defines the final position of the entity
  6176. * @param target defines where the entity should look at
  6177. * @param up defines the up vector for the entity
  6178. * @param result defines the target matrix
  6179. */
  6180. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6181. // Z axis
  6182. eye.subtractToRef(target, this._zAxis);
  6183. this._zAxis.normalize();
  6184. // X axis
  6185. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6186. if (this._xAxis.lengthSquared() === 0) {
  6187. this._xAxis.x = 1.0;
  6188. }
  6189. else {
  6190. this._xAxis.normalize();
  6191. }
  6192. // Y axis
  6193. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6194. this._yAxis.normalize();
  6195. // Eye angles
  6196. var ex = -Vector3.Dot(this._xAxis, eye);
  6197. var ey = -Vector3.Dot(this._yAxis, eye);
  6198. var ez = -Vector3.Dot(this._zAxis, eye);
  6199. 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);
  6200. };
  6201. /**
  6202. * Create a left-handed orthographic projection matrix
  6203. * @param width defines the viewport width
  6204. * @param height defines the viewport height
  6205. * @param znear defines the near clip plane
  6206. * @param zfar defines the far clip plane
  6207. * @returns a new matrix as a left-handed orthographic projection matrix
  6208. */
  6209. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6210. var matrix = Matrix.Zero();
  6211. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6212. return matrix;
  6213. };
  6214. /**
  6215. * Store a left-handed orthographic projection to a given matrix
  6216. * @param width defines the viewport width
  6217. * @param height defines the viewport height
  6218. * @param znear defines the near clip plane
  6219. * @param zfar defines the far clip plane
  6220. * @param result defines the target matrix
  6221. */
  6222. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6223. var n = znear;
  6224. var f = zfar;
  6225. var a = 2.0 / width;
  6226. var b = 2.0 / height;
  6227. var c = 2.0 / (f - n);
  6228. var d = -(f + n) / (f - n);
  6229. 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);
  6230. };
  6231. /**
  6232. * Create a left-handed orthographic projection matrix
  6233. * @param left defines the viewport left coordinate
  6234. * @param right defines the viewport right coordinate
  6235. * @param bottom defines the viewport bottom coordinate
  6236. * @param top defines the viewport top coordinate
  6237. * @param znear defines the near clip plane
  6238. * @param zfar defines the far clip plane
  6239. * @returns a new matrix as a left-handed orthographic projection matrix
  6240. */
  6241. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6242. var matrix = Matrix.Zero();
  6243. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6244. return matrix;
  6245. };
  6246. /**
  6247. * Stores a left-handed orthographic projection into a given matrix
  6248. * @param left defines the viewport left coordinate
  6249. * @param right defines the viewport right coordinate
  6250. * @param bottom defines the viewport bottom coordinate
  6251. * @param top defines the viewport top coordinate
  6252. * @param znear defines the near clip plane
  6253. * @param zfar defines the far clip plane
  6254. * @param result defines the target matrix
  6255. */
  6256. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6257. var n = znear;
  6258. var f = zfar;
  6259. var a = 2.0 / (right - left);
  6260. var b = 2.0 / (top - bottom);
  6261. var c = 2.0 / (f - n);
  6262. var d = -(f + n) / (f - n);
  6263. var i0 = (left + right) / (left - right);
  6264. var i1 = (top + bottom) / (bottom - top);
  6265. 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);
  6266. };
  6267. /**
  6268. * Creates a right-handed orthographic projection matrix
  6269. * @param left defines the viewport left coordinate
  6270. * @param right defines the viewport right coordinate
  6271. * @param bottom defines the viewport bottom coordinate
  6272. * @param top defines the viewport top coordinate
  6273. * @param znear defines the near clip plane
  6274. * @param zfar defines the far clip plane
  6275. * @returns a new matrix as a right-handed orthographic projection matrix
  6276. */
  6277. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6278. var matrix = Matrix.Zero();
  6279. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6280. return matrix;
  6281. };
  6282. /**
  6283. * Stores a right-handed orthographic projection into a given matrix
  6284. * @param left defines the viewport left coordinate
  6285. * @param right defines the viewport right coordinate
  6286. * @param bottom defines the viewport bottom coordinate
  6287. * @param top defines the viewport top coordinate
  6288. * @param znear defines the near clip plane
  6289. * @param zfar defines the far clip plane
  6290. * @param result defines the target matrix
  6291. */
  6292. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6293. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6294. result.m[10] *= -1.0;
  6295. };
  6296. /**
  6297. * Creates a left-handed perspective projection matrix
  6298. * @param width defines the viewport width
  6299. * @param height defines the viewport height
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @returns a new matrix as a left-handed perspective projection matrix
  6303. */
  6304. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6305. var matrix = Matrix.Zero();
  6306. var n = znear;
  6307. var f = zfar;
  6308. var a = 2.0 * n / width;
  6309. var b = 2.0 * n / height;
  6310. var c = (f + n) / (f - n);
  6311. var d = -2.0 * f * n / (f - n);
  6312. 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);
  6313. return matrix;
  6314. };
  6315. /**
  6316. * Creates a left-handed perspective projection matrix
  6317. * @param fov defines the horizontal field of view
  6318. * @param aspect defines the aspect ratio
  6319. * @param znear defines the near clip plane
  6320. * @param zfar defines the far clip plane
  6321. * @returns a new matrix as a left-handed perspective projection matrix
  6322. */
  6323. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6324. var matrix = Matrix.Zero();
  6325. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6326. return matrix;
  6327. };
  6328. /**
  6329. * Stores a left-handed perspective projection into a given matrix
  6330. * @param fov defines the horizontal field of view
  6331. * @param aspect defines the aspect ratio
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @param result defines the target matrix
  6335. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6336. */
  6337. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6338. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6339. var n = znear;
  6340. var f = zfar;
  6341. var t = 1.0 / (Math.tan(fov * 0.5));
  6342. var a = isVerticalFovFixed ? (t / aspect) : t;
  6343. var b = isVerticalFovFixed ? t : (t * aspect);
  6344. var c = (f + n) / (f - n);
  6345. var d = -2.0 * f * n / (f - n);
  6346. 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);
  6347. };
  6348. /**
  6349. * Creates a right-handed perspective projection matrix
  6350. * @param fov defines the horizontal field of view
  6351. * @param aspect defines the aspect ratio
  6352. * @param znear defines the near clip plane
  6353. * @param zfar defines the far clip plane
  6354. * @returns a new matrix as a right-handed perspective projection matrix
  6355. */
  6356. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6357. var matrix = Matrix.Zero();
  6358. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6359. return matrix;
  6360. };
  6361. /**
  6362. * Stores a right-handed perspective projection into a given matrix
  6363. * @param fov defines the horizontal field of view
  6364. * @param aspect defines the aspect ratio
  6365. * @param znear defines the near clip plane
  6366. * @param zfar defines the far clip plane
  6367. * @param result defines the target matrix
  6368. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6369. */
  6370. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6371. //alternatively this could be expressed as:
  6372. // m = PerspectiveFovLHToRef
  6373. // m[10] *= -1.0;
  6374. // m[11] *= -1.0;
  6375. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6376. var n = znear;
  6377. var f = zfar;
  6378. var t = 1.0 / (Math.tan(fov * 0.5));
  6379. var a = isVerticalFovFixed ? (t / aspect) : t;
  6380. var b = isVerticalFovFixed ? t : (t * aspect);
  6381. var c = -(f + n) / (f - n);
  6382. var d = -2 * f * n / (f - n);
  6383. 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);
  6384. };
  6385. /**
  6386. * Stores a perspective projection for WebVR info a given matrix
  6387. * @param fov defines the field of view
  6388. * @param znear defines the near clip plane
  6389. * @param zfar defines the far clip plane
  6390. * @param result defines the target matrix
  6391. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6392. */
  6393. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6394. if (rightHanded === void 0) { rightHanded = false; }
  6395. var rightHandedFactor = rightHanded ? -1 : 1;
  6396. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6397. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6398. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6399. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6400. var xScale = 2.0 / (leftTan + rightTan);
  6401. var yScale = 2.0 / (upTan + downTan);
  6402. result.m[0] = xScale;
  6403. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6404. result.m[5] = yScale;
  6405. result.m[6] = result.m[7] = 0.0;
  6406. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6407. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6408. result.m[10] = -zfar / (znear - zfar);
  6409. result.m[11] = 1.0 * rightHandedFactor;
  6410. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6411. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6412. result._markAsUpdated();
  6413. };
  6414. /**
  6415. * Computes a complete transformation matrix
  6416. * @param viewport defines the viewport to use
  6417. * @param world defines the world matrix
  6418. * @param view defines the view matrix
  6419. * @param projection defines the projection matrix
  6420. * @param zmin defines the near clip plane
  6421. * @param zmax defines the far clip plane
  6422. * @returns the transformation matrix
  6423. */
  6424. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6425. var cw = viewport.width;
  6426. var ch = viewport.height;
  6427. var cx = viewport.x;
  6428. var cy = viewport.y;
  6429. 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);
  6430. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6431. };
  6432. /**
  6433. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6434. * @param matrix defines the matrix to use
  6435. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6436. */
  6437. Matrix.GetAsMatrix2x2 = function (matrix) {
  6438. return new Float32Array([
  6439. matrix.m[0], matrix.m[1],
  6440. matrix.m[4], matrix.m[5]
  6441. ]);
  6442. };
  6443. /**
  6444. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6445. * @param matrix defines the matrix to use
  6446. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6447. */
  6448. Matrix.GetAsMatrix3x3 = function (matrix) {
  6449. return new Float32Array([
  6450. matrix.m[0], matrix.m[1], matrix.m[2],
  6451. matrix.m[4], matrix.m[5], matrix.m[6],
  6452. matrix.m[8], matrix.m[9], matrix.m[10]
  6453. ]);
  6454. };
  6455. /**
  6456. * Compute the transpose of a given matrix
  6457. * @param matrix defines the matrix to transpose
  6458. * @returns the new matrix
  6459. */
  6460. Matrix.Transpose = function (matrix) {
  6461. var result = new Matrix();
  6462. Matrix.TransposeToRef(matrix, result);
  6463. return result;
  6464. };
  6465. /**
  6466. * Compute the transpose of a matrix and store it in a target matrix
  6467. * @param matrix defines the matrix to transpose
  6468. * @param result defines the target matrix
  6469. */
  6470. Matrix.TransposeToRef = function (matrix, result) {
  6471. result.m[0] = matrix.m[0];
  6472. result.m[1] = matrix.m[4];
  6473. result.m[2] = matrix.m[8];
  6474. result.m[3] = matrix.m[12];
  6475. result.m[4] = matrix.m[1];
  6476. result.m[5] = matrix.m[5];
  6477. result.m[6] = matrix.m[9];
  6478. result.m[7] = matrix.m[13];
  6479. result.m[8] = matrix.m[2];
  6480. result.m[9] = matrix.m[6];
  6481. result.m[10] = matrix.m[10];
  6482. result.m[11] = matrix.m[14];
  6483. result.m[12] = matrix.m[3];
  6484. result.m[13] = matrix.m[7];
  6485. result.m[14] = matrix.m[11];
  6486. result.m[15] = matrix.m[15];
  6487. };
  6488. /**
  6489. * Computes a reflection matrix from a plane
  6490. * @param plane defines the reflection plane
  6491. * @returns a new matrix
  6492. */
  6493. Matrix.Reflection = function (plane) {
  6494. var matrix = new Matrix();
  6495. Matrix.ReflectionToRef(plane, matrix);
  6496. return matrix;
  6497. };
  6498. /**
  6499. * Computes a reflection matrix from a plane
  6500. * @param plane defines the reflection plane
  6501. * @param result defines the target matrix
  6502. */
  6503. Matrix.ReflectionToRef = function (plane, result) {
  6504. plane.normalize();
  6505. var x = plane.normal.x;
  6506. var y = plane.normal.y;
  6507. var z = plane.normal.z;
  6508. var temp = -2 * x;
  6509. var temp2 = -2 * y;
  6510. var temp3 = -2 * z;
  6511. result.m[0] = (temp * x) + 1;
  6512. result.m[1] = temp2 * x;
  6513. result.m[2] = temp3 * x;
  6514. result.m[3] = 0.0;
  6515. result.m[4] = temp * y;
  6516. result.m[5] = (temp2 * y) + 1;
  6517. result.m[6] = temp3 * y;
  6518. result.m[7] = 0.0;
  6519. result.m[8] = temp * z;
  6520. result.m[9] = temp2 * z;
  6521. result.m[10] = (temp3 * z) + 1;
  6522. result.m[11] = 0.0;
  6523. result.m[12] = temp * plane.d;
  6524. result.m[13] = temp2 * plane.d;
  6525. result.m[14] = temp3 * plane.d;
  6526. result.m[15] = 1.0;
  6527. result._markAsUpdated();
  6528. };
  6529. /**
  6530. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6531. * @param xaxis defines the value of the 1st axis
  6532. * @param yaxis defines the value of the 2nd axis
  6533. * @param zaxis defines the value of the 3rd axis
  6534. * @param result defines the target matrix
  6535. */
  6536. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6537. result.m[0] = xaxis.x;
  6538. result.m[1] = xaxis.y;
  6539. result.m[2] = xaxis.z;
  6540. result.m[3] = 0.0;
  6541. result.m[4] = yaxis.x;
  6542. result.m[5] = yaxis.y;
  6543. result.m[6] = yaxis.z;
  6544. result.m[7] = 0.0;
  6545. result.m[8] = zaxis.x;
  6546. result.m[9] = zaxis.y;
  6547. result.m[10] = zaxis.z;
  6548. result.m[11] = 0.0;
  6549. result.m[12] = 0.0;
  6550. result.m[13] = 0.0;
  6551. result.m[14] = 0.0;
  6552. result.m[15] = 1.0;
  6553. result._markAsUpdated();
  6554. };
  6555. /**
  6556. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6557. * @param quat defines the quaternion to use
  6558. * @param result defines the target matrix
  6559. */
  6560. Matrix.FromQuaternionToRef = function (quat, result) {
  6561. var xx = quat.x * quat.x;
  6562. var yy = quat.y * quat.y;
  6563. var zz = quat.z * quat.z;
  6564. var xy = quat.x * quat.y;
  6565. var zw = quat.z * quat.w;
  6566. var zx = quat.z * quat.x;
  6567. var yw = quat.y * quat.w;
  6568. var yz = quat.y * quat.z;
  6569. var xw = quat.x * quat.w;
  6570. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6571. result.m[1] = 2.0 * (xy + zw);
  6572. result.m[2] = 2.0 * (zx - yw);
  6573. result.m[3] = 0.0;
  6574. result.m[4] = 2.0 * (xy - zw);
  6575. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6576. result.m[6] = 2.0 * (yz + xw);
  6577. result.m[7] = 0.0;
  6578. result.m[8] = 2.0 * (zx + yw);
  6579. result.m[9] = 2.0 * (yz - xw);
  6580. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6581. result.m[11] = 0.0;
  6582. result.m[12] = 0.0;
  6583. result.m[13] = 0.0;
  6584. result.m[14] = 0.0;
  6585. result.m[15] = 1.0;
  6586. result._markAsUpdated();
  6587. };
  6588. Matrix._tempQuaternion = new Quaternion();
  6589. Matrix._xAxis = Vector3.Zero();
  6590. Matrix._yAxis = Vector3.Zero();
  6591. Matrix._zAxis = Vector3.Zero();
  6592. Matrix._updateFlagSeed = 0;
  6593. Matrix._identityReadOnly = Matrix.Identity();
  6594. return Matrix;
  6595. }());
  6596. BABYLON.Matrix = Matrix;
  6597. var Plane = /** @class */ (function () {
  6598. /**
  6599. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6600. */
  6601. function Plane(a, b, c, d) {
  6602. this.normal = new Vector3(a, b, c);
  6603. this.d = d;
  6604. }
  6605. /**
  6606. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6607. */
  6608. Plane.prototype.asArray = function () {
  6609. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6610. };
  6611. // Methods
  6612. /**
  6613. * Returns a new plane copied from the current Plane.
  6614. */
  6615. Plane.prototype.clone = function () {
  6616. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6617. };
  6618. /**
  6619. * Returns the string "Plane".
  6620. */
  6621. Plane.prototype.getClassName = function () {
  6622. return "Plane";
  6623. };
  6624. /**
  6625. * Returns the Plane hash code.
  6626. */
  6627. Plane.prototype.getHashCode = function () {
  6628. var hash = this.normal.getHashCode();
  6629. hash = (hash * 397) ^ (this.d || 0);
  6630. return hash;
  6631. };
  6632. /**
  6633. * Normalize the current Plane in place.
  6634. * Returns the updated Plane.
  6635. */
  6636. Plane.prototype.normalize = function () {
  6637. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6638. var magnitude = 0.0;
  6639. if (norm !== 0) {
  6640. magnitude = 1.0 / norm;
  6641. }
  6642. this.normal.x *= magnitude;
  6643. this.normal.y *= magnitude;
  6644. this.normal.z *= magnitude;
  6645. this.d *= magnitude;
  6646. return this;
  6647. };
  6648. /**
  6649. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6650. */
  6651. Plane.prototype.transform = function (transformation) {
  6652. var transposedMatrix = Matrix.Transpose(transformation);
  6653. var x = this.normal.x;
  6654. var y = this.normal.y;
  6655. var z = this.normal.z;
  6656. var d = this.d;
  6657. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6658. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6659. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6660. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6661. return new Plane(normalX, normalY, normalZ, finalD);
  6662. };
  6663. /**
  6664. * Returns the dot product (float) of the point coordinates and the plane normal.
  6665. */
  6666. Plane.prototype.dotCoordinate = function (point) {
  6667. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6668. };
  6669. /**
  6670. * Updates the current Plane from the plane defined by the three given points.
  6671. * Returns the updated Plane.
  6672. */
  6673. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6674. var x1 = point2.x - point1.x;
  6675. var y1 = point2.y - point1.y;
  6676. var z1 = point2.z - point1.z;
  6677. var x2 = point3.x - point1.x;
  6678. var y2 = point3.y - point1.y;
  6679. var z2 = point3.z - point1.z;
  6680. var yz = (y1 * z2) - (z1 * y2);
  6681. var xz = (z1 * x2) - (x1 * z2);
  6682. var xy = (x1 * y2) - (y1 * x2);
  6683. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6684. var invPyth;
  6685. if (pyth !== 0) {
  6686. invPyth = 1.0 / pyth;
  6687. }
  6688. else {
  6689. invPyth = 0.0;
  6690. }
  6691. this.normal.x = yz * invPyth;
  6692. this.normal.y = xz * invPyth;
  6693. this.normal.z = xy * invPyth;
  6694. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6695. return this;
  6696. };
  6697. /**
  6698. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6699. */
  6700. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6701. var dot = Vector3.Dot(this.normal, direction);
  6702. return (dot <= epsilon);
  6703. };
  6704. /**
  6705. * Returns the signed distance (float) from the given point to the Plane.
  6706. */
  6707. Plane.prototype.signedDistanceTo = function (point) {
  6708. return Vector3.Dot(point, this.normal) + this.d;
  6709. };
  6710. // Statics
  6711. /**
  6712. * Returns a new Plane from the given array.
  6713. */
  6714. Plane.FromArray = function (array) {
  6715. return new Plane(array[0], array[1], array[2], array[3]);
  6716. };
  6717. /**
  6718. * Returns a new Plane defined by the three given points.
  6719. */
  6720. Plane.FromPoints = function (point1, point2, point3) {
  6721. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6722. result.copyFromPoints(point1, point2, point3);
  6723. return result;
  6724. };
  6725. /**
  6726. * Returns a new Plane the normal vector to this plane at the given origin point.
  6727. * Note : the vector "normal" is updated because normalized.
  6728. */
  6729. Plane.FromPositionAndNormal = function (origin, normal) {
  6730. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6731. normal.normalize();
  6732. result.normal = normal;
  6733. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6734. return result;
  6735. };
  6736. /**
  6737. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6738. */
  6739. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6740. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6741. return Vector3.Dot(point, normal) + d;
  6742. };
  6743. return Plane;
  6744. }());
  6745. BABYLON.Plane = Plane;
  6746. var Viewport = /** @class */ (function () {
  6747. /**
  6748. * Creates a Viewport object located at (x, y) and sized (width, height).
  6749. */
  6750. function Viewport(x, y, width, height) {
  6751. this.x = x;
  6752. this.y = y;
  6753. this.width = width;
  6754. this.height = height;
  6755. }
  6756. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6757. if (renderWidthOrEngine.getRenderWidth) {
  6758. var engine = renderWidthOrEngine;
  6759. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6760. }
  6761. var renderWidth = renderWidthOrEngine;
  6762. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6763. };
  6764. /**
  6765. * Returns a new Viewport copied from the current one.
  6766. */
  6767. Viewport.prototype.clone = function () {
  6768. return new Viewport(this.x, this.y, this.width, this.height);
  6769. };
  6770. return Viewport;
  6771. }());
  6772. BABYLON.Viewport = Viewport;
  6773. var Frustum = /** @class */ (function () {
  6774. function Frustum() {
  6775. }
  6776. /**
  6777. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6778. */
  6779. Frustum.GetPlanes = function (transform) {
  6780. var frustumPlanes = [];
  6781. for (var index = 0; index < 6; index++) {
  6782. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6783. }
  6784. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6785. return frustumPlanes;
  6786. };
  6787. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6788. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6789. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6790. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6791. frustumPlane.d = transform.m[15] + transform.m[14];
  6792. frustumPlane.normalize();
  6793. };
  6794. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6795. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6796. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6797. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6798. frustumPlane.d = transform.m[15] - transform.m[14];
  6799. frustumPlane.normalize();
  6800. };
  6801. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6802. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6803. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6804. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6805. frustumPlane.d = transform.m[15] + transform.m[12];
  6806. frustumPlane.normalize();
  6807. };
  6808. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6809. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6810. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6811. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6812. frustumPlane.d = transform.m[15] - transform.m[12];
  6813. frustumPlane.normalize();
  6814. };
  6815. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6816. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6817. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6818. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6819. frustumPlane.d = transform.m[15] - transform.m[13];
  6820. frustumPlane.normalize();
  6821. };
  6822. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6823. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6824. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6825. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6826. frustumPlane.d = transform.m[15] + transform.m[13];
  6827. frustumPlane.normalize();
  6828. };
  6829. /**
  6830. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6831. */
  6832. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6833. // Near
  6834. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6835. // Far
  6836. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6837. // Left
  6838. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6839. // Right
  6840. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6841. // Top
  6842. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6843. // Bottom
  6844. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6845. };
  6846. return Frustum;
  6847. }());
  6848. BABYLON.Frustum = Frustum;
  6849. /** Defines supported spaces */
  6850. var Space;
  6851. (function (Space) {
  6852. /** Local (object) space */
  6853. Space[Space["LOCAL"] = 0] = "LOCAL";
  6854. /** World space */
  6855. Space[Space["WORLD"] = 1] = "WORLD";
  6856. /** Bone space */
  6857. Space[Space["BONE"] = 2] = "BONE";
  6858. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6859. /** Defines the 3 main axes */
  6860. var Axis = /** @class */ (function () {
  6861. function Axis() {
  6862. }
  6863. /** X axis */
  6864. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6865. /** Y axis */
  6866. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6867. /** Z axis */
  6868. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6869. return Axis;
  6870. }());
  6871. BABYLON.Axis = Axis;
  6872. ;
  6873. var BezierCurve = /** @class */ (function () {
  6874. function BezierCurve() {
  6875. }
  6876. /**
  6877. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6878. */
  6879. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6880. // Extract X (which is equal to time here)
  6881. var f0 = 1 - 3 * x2 + 3 * x1;
  6882. var f1 = 3 * x2 - 6 * x1;
  6883. var f2 = 3 * x1;
  6884. var refinedT = t;
  6885. for (var i = 0; i < 5; i++) {
  6886. var refinedT2 = refinedT * refinedT;
  6887. var refinedT3 = refinedT2 * refinedT;
  6888. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6889. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6890. refinedT -= (x - t) * slope;
  6891. refinedT = Math.min(1, Math.max(0, refinedT));
  6892. }
  6893. // Resolve cubic bezier for the given x
  6894. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6895. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6896. Math.pow(refinedT, 3);
  6897. };
  6898. return BezierCurve;
  6899. }());
  6900. BABYLON.BezierCurve = BezierCurve;
  6901. /**
  6902. * Defines potential orientation for back face culling
  6903. */
  6904. var Orientation;
  6905. (function (Orientation) {
  6906. /**
  6907. * Clockwise
  6908. */
  6909. Orientation[Orientation["CW"] = 0] = "CW";
  6910. /** Counter clockwise */
  6911. Orientation[Orientation["CCW"] = 1] = "CCW";
  6912. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6913. /**
  6914. * Defines angle representation
  6915. */
  6916. var Angle = /** @class */ (function () {
  6917. /**
  6918. * Creates an Angle object of "radians" radians (float).
  6919. */
  6920. function Angle(radians) {
  6921. this._radians = radians;
  6922. if (this._radians < 0.0)
  6923. this._radians += (2.0 * Math.PI);
  6924. }
  6925. /**
  6926. * Get value in degrees
  6927. * @returns the Angle value in degrees (float)
  6928. */
  6929. Angle.prototype.degrees = function () {
  6930. return this._radians * 180.0 / Math.PI;
  6931. };
  6932. /**
  6933. * Get value in radians
  6934. * @returns the Angle value in radians (float)
  6935. */
  6936. Angle.prototype.radians = function () {
  6937. return this._radians;
  6938. };
  6939. /**
  6940. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6941. * @param a defines first vector
  6942. * @param b defines second vector
  6943. * @returns a new Angle
  6944. */
  6945. Angle.BetweenTwoPoints = function (a, b) {
  6946. var delta = b.subtract(a);
  6947. var theta = Math.atan2(delta.y, delta.x);
  6948. return new Angle(theta);
  6949. };
  6950. /**
  6951. * Gets a new Angle object from the given float in radians
  6952. * @param radians defines the angle value in radians
  6953. * @returns a new Angle
  6954. */
  6955. Angle.FromRadians = function (radians) {
  6956. return new Angle(radians);
  6957. };
  6958. /**
  6959. * Gets a new Angle object from the given float in degrees
  6960. * @param degrees defines the angle value in degrees
  6961. * @returns a new Angle
  6962. */
  6963. Angle.FromDegrees = function (degrees) {
  6964. return new Angle(degrees * Math.PI / 180.0);
  6965. };
  6966. return Angle;
  6967. }());
  6968. BABYLON.Angle = Angle;
  6969. var Arc2 = /** @class */ (function () {
  6970. /**
  6971. * Creates an Arc object from the three given points : start, middle and end.
  6972. */
  6973. function Arc2(startPoint, midPoint, endPoint) {
  6974. this.startPoint = startPoint;
  6975. this.midPoint = midPoint;
  6976. this.endPoint = endPoint;
  6977. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6978. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6979. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6980. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6981. 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);
  6982. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6983. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6984. var a1 = this.startAngle.degrees();
  6985. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6986. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6987. // angles correction
  6988. if (a2 - a1 > +180.0)
  6989. a2 -= 360.0;
  6990. if (a2 - a1 < -180.0)
  6991. a2 += 360.0;
  6992. if (a3 - a2 > +180.0)
  6993. a3 -= 360.0;
  6994. if (a3 - a2 < -180.0)
  6995. a3 += 360.0;
  6996. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6997. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6998. }
  6999. return Arc2;
  7000. }());
  7001. BABYLON.Arc2 = Arc2;
  7002. var Path2 = /** @class */ (function () {
  7003. /**
  7004. * Creates a Path2 object from the starting 2D coordinates x and y.
  7005. */
  7006. function Path2(x, y) {
  7007. this._points = new Array();
  7008. this._length = 0.0;
  7009. this.closed = false;
  7010. this._points.push(new Vector2(x, y));
  7011. }
  7012. /**
  7013. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7014. * Returns the updated Path2.
  7015. */
  7016. Path2.prototype.addLineTo = function (x, y) {
  7017. if (this.closed) {
  7018. return this;
  7019. }
  7020. var newPoint = new Vector2(x, y);
  7021. var previousPoint = this._points[this._points.length - 1];
  7022. this._points.push(newPoint);
  7023. this._length += newPoint.subtract(previousPoint).length();
  7024. return this;
  7025. };
  7026. /**
  7027. * 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.
  7028. * Returns the updated Path2.
  7029. */
  7030. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7031. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7032. if (this.closed) {
  7033. return this;
  7034. }
  7035. var startPoint = this._points[this._points.length - 1];
  7036. var midPoint = new Vector2(midX, midY);
  7037. var endPoint = new Vector2(endX, endY);
  7038. var arc = new Arc2(startPoint, midPoint, endPoint);
  7039. var increment = arc.angle.radians() / numberOfSegments;
  7040. if (arc.orientation === Orientation.CW)
  7041. increment *= -1;
  7042. var currentAngle = arc.startAngle.radians() + increment;
  7043. for (var i = 0; i < numberOfSegments; i++) {
  7044. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7045. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7046. this.addLineTo(x, y);
  7047. currentAngle += increment;
  7048. }
  7049. return this;
  7050. };
  7051. /**
  7052. * Closes the Path2.
  7053. * Returns the Path2.
  7054. */
  7055. Path2.prototype.close = function () {
  7056. this.closed = true;
  7057. return this;
  7058. };
  7059. /**
  7060. * Returns the Path2 total length (float).
  7061. */
  7062. Path2.prototype.length = function () {
  7063. var result = this._length;
  7064. if (!this.closed) {
  7065. var lastPoint = this._points[this._points.length - 1];
  7066. var firstPoint = this._points[0];
  7067. result += (firstPoint.subtract(lastPoint).length());
  7068. }
  7069. return result;
  7070. };
  7071. /**
  7072. * Returns the Path2 internal array of points.
  7073. */
  7074. Path2.prototype.getPoints = function () {
  7075. return this._points;
  7076. };
  7077. /**
  7078. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7079. */
  7080. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7081. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7082. return Vector2.Zero();
  7083. }
  7084. var lengthPosition = normalizedLengthPosition * this.length();
  7085. var previousOffset = 0;
  7086. for (var i = 0; i < this._points.length; i++) {
  7087. var j = (i + 1) % this._points.length;
  7088. var a = this._points[i];
  7089. var b = this._points[j];
  7090. var bToA = b.subtract(a);
  7091. var nextOffset = (bToA.length() + previousOffset);
  7092. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7093. var dir = bToA.normalize();
  7094. var localOffset = lengthPosition - previousOffset;
  7095. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7096. }
  7097. previousOffset = nextOffset;
  7098. }
  7099. return Vector2.Zero();
  7100. };
  7101. /**
  7102. * Returns a new Path2 starting at the coordinates (x, y).
  7103. */
  7104. Path2.StartingAt = function (x, y) {
  7105. return new Path2(x, y);
  7106. };
  7107. return Path2;
  7108. }());
  7109. BABYLON.Path2 = Path2;
  7110. var Path3D = /** @class */ (function () {
  7111. /**
  7112. * new Path3D(path, normal, raw)
  7113. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7114. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7115. * path : an array of Vector3, the curve axis of the Path3D
  7116. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7117. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7118. */
  7119. function Path3D(path, firstNormal, raw) {
  7120. if (firstNormal === void 0) { firstNormal = null; }
  7121. this.path = path;
  7122. this._curve = new Array();
  7123. this._distances = new Array();
  7124. this._tangents = new Array();
  7125. this._normals = new Array();
  7126. this._binormals = new Array();
  7127. for (var p = 0; p < path.length; p++) {
  7128. this._curve[p] = path[p].clone(); // hard copy
  7129. }
  7130. this._raw = raw || false;
  7131. this._compute(firstNormal);
  7132. }
  7133. /**
  7134. * Returns the Path3D array of successive Vector3 designing its curve.
  7135. */
  7136. Path3D.prototype.getCurve = function () {
  7137. return this._curve;
  7138. };
  7139. /**
  7140. * Returns an array populated with tangent vectors on each Path3D curve point.
  7141. */
  7142. Path3D.prototype.getTangents = function () {
  7143. return this._tangents;
  7144. };
  7145. /**
  7146. * Returns an array populated with normal vectors on each Path3D curve point.
  7147. */
  7148. Path3D.prototype.getNormals = function () {
  7149. return this._normals;
  7150. };
  7151. /**
  7152. * Returns an array populated with binormal vectors on each Path3D curve point.
  7153. */
  7154. Path3D.prototype.getBinormals = function () {
  7155. return this._binormals;
  7156. };
  7157. /**
  7158. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7159. */
  7160. Path3D.prototype.getDistances = function () {
  7161. return this._distances;
  7162. };
  7163. /**
  7164. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7165. * Returns the same object updated.
  7166. */
  7167. Path3D.prototype.update = function (path, firstNormal) {
  7168. if (firstNormal === void 0) { firstNormal = null; }
  7169. for (var p = 0; p < path.length; p++) {
  7170. this._curve[p].x = path[p].x;
  7171. this._curve[p].y = path[p].y;
  7172. this._curve[p].z = path[p].z;
  7173. }
  7174. this._compute(firstNormal);
  7175. return this;
  7176. };
  7177. // private function compute() : computes tangents, normals and binormals
  7178. Path3D.prototype._compute = function (firstNormal) {
  7179. var l = this._curve.length;
  7180. // first and last tangents
  7181. this._tangents[0] = this._getFirstNonNullVector(0);
  7182. if (!this._raw) {
  7183. this._tangents[0].normalize();
  7184. }
  7185. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7186. if (!this._raw) {
  7187. this._tangents[l - 1].normalize();
  7188. }
  7189. // normals and binormals at first point : arbitrary vector with _normalVector()
  7190. var tg0 = this._tangents[0];
  7191. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7192. this._normals[0] = pp0;
  7193. if (!this._raw) {
  7194. this._normals[0].normalize();
  7195. }
  7196. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7197. if (!this._raw) {
  7198. this._binormals[0].normalize();
  7199. }
  7200. this._distances[0] = 0.0;
  7201. // normals and binormals : next points
  7202. var prev; // previous vector (segment)
  7203. var cur; // current vector (segment)
  7204. var curTang; // current tangent
  7205. // previous normal
  7206. var prevBinor; // previous binormal
  7207. for (var i = 1; i < l; i++) {
  7208. // tangents
  7209. prev = this._getLastNonNullVector(i);
  7210. if (i < l - 1) {
  7211. cur = this._getFirstNonNullVector(i);
  7212. this._tangents[i] = prev.add(cur);
  7213. this._tangents[i].normalize();
  7214. }
  7215. this._distances[i] = this._distances[i - 1] + prev.length();
  7216. // normals and binormals
  7217. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7218. curTang = this._tangents[i];
  7219. prevBinor = this._binormals[i - 1];
  7220. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7221. if (!this._raw) {
  7222. this._normals[i].normalize();
  7223. }
  7224. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7225. if (!this._raw) {
  7226. this._binormals[i].normalize();
  7227. }
  7228. }
  7229. };
  7230. // private function getFirstNonNullVector(index)
  7231. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7232. Path3D.prototype._getFirstNonNullVector = function (index) {
  7233. var i = 1;
  7234. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7235. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7236. i++;
  7237. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7238. }
  7239. return nNVector;
  7240. };
  7241. // private function getLastNonNullVector(index)
  7242. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7243. Path3D.prototype._getLastNonNullVector = function (index) {
  7244. var i = 1;
  7245. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7246. while (nLVector.length() === 0 && index > i + 1) {
  7247. i++;
  7248. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7249. }
  7250. return nLVector;
  7251. };
  7252. // private function normalVector(v0, vt, va) :
  7253. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7254. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7255. Path3D.prototype._normalVector = function (v0, vt, va) {
  7256. var normal0;
  7257. var tgl = vt.length();
  7258. if (tgl === 0.0) {
  7259. tgl = 1.0;
  7260. }
  7261. if (va === undefined || va === null) {
  7262. var point;
  7263. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7264. point = new Vector3(0.0, -1.0, 0.0);
  7265. }
  7266. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7267. point = new Vector3(1.0, 0.0, 0.0);
  7268. }
  7269. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7270. point = new Vector3(0.0, 0.0, 1.0);
  7271. }
  7272. else {
  7273. point = Vector3.Zero();
  7274. }
  7275. normal0 = Vector3.Cross(vt, point);
  7276. }
  7277. else {
  7278. normal0 = Vector3.Cross(vt, va);
  7279. Vector3.CrossToRef(normal0, vt, normal0);
  7280. }
  7281. normal0.normalize();
  7282. return normal0;
  7283. };
  7284. return Path3D;
  7285. }());
  7286. BABYLON.Path3D = Path3D;
  7287. var Curve3 = /** @class */ (function () {
  7288. /**
  7289. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7290. * A Curve3 is designed from a series of successive Vector3.
  7291. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7292. */
  7293. function Curve3(points) {
  7294. this._length = 0.0;
  7295. this._points = points;
  7296. this._length = this._computeLength(points);
  7297. }
  7298. /**
  7299. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7300. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7301. * @param v1 (Vector3) the control point
  7302. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7303. * @param nbPoints (integer) the wanted number of points in the curve
  7304. */
  7305. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7306. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7307. var bez = new Array();
  7308. var equation = function (t, val0, val1, val2) {
  7309. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7310. return res;
  7311. };
  7312. for (var i = 0; i <= nbPoints; i++) {
  7313. 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)));
  7314. }
  7315. return new Curve3(bez);
  7316. };
  7317. /**
  7318. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7319. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7320. * @param v1 (Vector3) the first control point
  7321. * @param v2 (Vector3) the second control point
  7322. * @param v3 (Vector3) the end point of the Cubic Bezier
  7323. * @param nbPoints (integer) the wanted number of points in the curve
  7324. */
  7325. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7326. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7327. var bez = new Array();
  7328. var equation = function (t, val0, val1, val2, val3) {
  7329. 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;
  7330. return res;
  7331. };
  7332. for (var i = 0; i <= nbPoints; i++) {
  7333. 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)));
  7334. }
  7335. return new Curve3(bez);
  7336. };
  7337. /**
  7338. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7339. * @param p1 (Vector3) the origin point of the Hermite Spline
  7340. * @param t1 (Vector3) the tangent vector at the origin point
  7341. * @param p2 (Vector3) the end point of the Hermite Spline
  7342. * @param t2 (Vector3) the tangent vector at the end point
  7343. * @param nbPoints (integer) the wanted number of points in the curve
  7344. */
  7345. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7346. var hermite = new Array();
  7347. var step = 1.0 / nbPoints;
  7348. for (var i = 0; i <= nbPoints; i++) {
  7349. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7350. }
  7351. return new Curve3(hermite);
  7352. };
  7353. /**
  7354. * Returns a Curve3 object along a CatmullRom Spline curve :
  7355. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7356. * @param nbPoints (integer) the wanted number of points between each curve control points
  7357. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7358. */
  7359. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7360. var catmullRom = new Array();
  7361. var step = 1.0 / nbPoints;
  7362. var amount = 0.0;
  7363. if (closed) {
  7364. var pointsCount = points.length;
  7365. for (var i = 0; i < pointsCount; i++) {
  7366. amount = 0;
  7367. for (var c = 0; c < nbPoints; c++) {
  7368. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7369. amount += step;
  7370. }
  7371. }
  7372. catmullRom.push(catmullRom[0]);
  7373. }
  7374. else {
  7375. var totalPoints = new Array();
  7376. totalPoints.push(points[0].clone());
  7377. Array.prototype.push.apply(totalPoints, points);
  7378. totalPoints.push(points[points.length - 1].clone());
  7379. for (var i = 0; i < totalPoints.length - 3; i++) {
  7380. amount = 0;
  7381. for (var c = 0; c < nbPoints; c++) {
  7382. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7383. amount += step;
  7384. }
  7385. }
  7386. i--;
  7387. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7388. }
  7389. return new Curve3(catmullRom);
  7390. };
  7391. /**
  7392. * Returns the Curve3 stored array of successive Vector3
  7393. */
  7394. Curve3.prototype.getPoints = function () {
  7395. return this._points;
  7396. };
  7397. /**
  7398. * Returns the computed length (float) of the curve.
  7399. */
  7400. Curve3.prototype.length = function () {
  7401. return this._length;
  7402. };
  7403. /**
  7404. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7405. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7406. * curveA and curveB keep unchanged.
  7407. */
  7408. Curve3.prototype.continue = function (curve) {
  7409. var lastPoint = this._points[this._points.length - 1];
  7410. var continuedPoints = this._points.slice();
  7411. var curvePoints = curve.getPoints();
  7412. for (var i = 1; i < curvePoints.length; i++) {
  7413. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7414. }
  7415. var continuedCurve = new Curve3(continuedPoints);
  7416. return continuedCurve;
  7417. };
  7418. Curve3.prototype._computeLength = function (path) {
  7419. var l = 0;
  7420. for (var i = 1; i < path.length; i++) {
  7421. l += (path[i].subtract(path[i - 1])).length();
  7422. }
  7423. return l;
  7424. };
  7425. return Curve3;
  7426. }());
  7427. BABYLON.Curve3 = Curve3;
  7428. // Vertex formats
  7429. var PositionNormalVertex = /** @class */ (function () {
  7430. function PositionNormalVertex(position, normal) {
  7431. if (position === void 0) { position = Vector3.Zero(); }
  7432. if (normal === void 0) { normal = Vector3.Up(); }
  7433. this.position = position;
  7434. this.normal = normal;
  7435. }
  7436. PositionNormalVertex.prototype.clone = function () {
  7437. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7438. };
  7439. return PositionNormalVertex;
  7440. }());
  7441. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7442. var PositionNormalTextureVertex = /** @class */ (function () {
  7443. function PositionNormalTextureVertex(position, normal, uv) {
  7444. if (position === void 0) { position = Vector3.Zero(); }
  7445. if (normal === void 0) { normal = Vector3.Up(); }
  7446. if (uv === void 0) { uv = Vector2.Zero(); }
  7447. this.position = position;
  7448. this.normal = normal;
  7449. this.uv = uv;
  7450. }
  7451. PositionNormalTextureVertex.prototype.clone = function () {
  7452. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7453. };
  7454. return PositionNormalTextureVertex;
  7455. }());
  7456. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7457. // Temporary pre-allocated objects for engine internal use
  7458. // usage in any internal function :
  7459. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7460. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7461. var Tmp = /** @class */ (function () {
  7462. function Tmp() {
  7463. }
  7464. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7465. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7466. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7467. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7468. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7469. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7470. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7471. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7472. Matrix.Zero(), Matrix.Zero(),
  7473. Matrix.Zero(), Matrix.Zero(),
  7474. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7475. return Tmp;
  7476. }());
  7477. BABYLON.Tmp = Tmp;
  7478. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7479. var MathTmp = /** @class */ (function () {
  7480. function MathTmp() {
  7481. }
  7482. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7483. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7484. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7485. return MathTmp;
  7486. }());
  7487. })(BABYLON || (BABYLON = {}));
  7488. //# sourceMappingURL=babylon.math.js.map
  7489. var BABYLON;
  7490. (function (BABYLON) {
  7491. var Scalar = /** @class */ (function () {
  7492. function Scalar() {
  7493. }
  7494. /**
  7495. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7496. */
  7497. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7498. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7499. var num = a - b;
  7500. return -epsilon <= num && num <= epsilon;
  7501. };
  7502. /**
  7503. * Returns a string : the upper case translation of the number i to hexadecimal.
  7504. */
  7505. Scalar.ToHex = function (i) {
  7506. var str = i.toString(16);
  7507. if (i <= 15) {
  7508. return ("0" + str).toUpperCase();
  7509. }
  7510. return str.toUpperCase();
  7511. };
  7512. /**
  7513. * Returns -1 if value is negative and +1 is value is positive.
  7514. * Returns the value itself if it's equal to zero.
  7515. */
  7516. Scalar.Sign = function (value) {
  7517. value = +value; // convert to a number
  7518. if (value === 0 || isNaN(value))
  7519. return value;
  7520. return value > 0 ? 1 : -1;
  7521. };
  7522. /**
  7523. * Returns the value itself if it's between min and max.
  7524. * Returns min if the value is lower than min.
  7525. * Returns max if the value is greater than max.
  7526. */
  7527. Scalar.Clamp = function (value, min, max) {
  7528. if (min === void 0) { min = 0; }
  7529. if (max === void 0) { max = 1; }
  7530. return Math.min(max, Math.max(min, value));
  7531. };
  7532. /**
  7533. * Returns the log2 of value.
  7534. */
  7535. Scalar.Log2 = function (value) {
  7536. return Math.log(value) * Math.LOG2E;
  7537. };
  7538. /**
  7539. * Loops the value, so that it is never larger than length and never smaller than 0.
  7540. *
  7541. * This is similar to the modulo operator but it works with floating point numbers.
  7542. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7543. * With t = 5 and length = 2.5, the result would be 0.0.
  7544. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7545. */
  7546. Scalar.Repeat = function (value, length) {
  7547. return value - Math.floor(value / length) * length;
  7548. };
  7549. /**
  7550. * Normalize the value between 0.0 and 1.0 using min and max values
  7551. */
  7552. Scalar.Normalize = function (value, min, max) {
  7553. return (value - min) / (max - min);
  7554. };
  7555. /**
  7556. * Denormalize the value from 0.0 and 1.0 using min and max values
  7557. */
  7558. Scalar.Denormalize = function (normalized, min, max) {
  7559. return (normalized * (max - min) + min);
  7560. };
  7561. /**
  7562. * Calculates the shortest difference between two given angles given in degrees.
  7563. */
  7564. Scalar.DeltaAngle = function (current, target) {
  7565. var num = Scalar.Repeat(target - current, 360.0);
  7566. if (num > 180.0) {
  7567. num -= 360.0;
  7568. }
  7569. return num;
  7570. };
  7571. /**
  7572. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7573. *
  7574. * The returned value will move back and forth between 0 and length
  7575. */
  7576. Scalar.PingPong = function (tx, length) {
  7577. var t = Scalar.Repeat(tx, length * 2.0);
  7578. return length - Math.abs(t - length);
  7579. };
  7580. /**
  7581. * Interpolates between min and max with smoothing at the limits.
  7582. *
  7583. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7584. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7585. */
  7586. Scalar.SmoothStep = function (from, to, tx) {
  7587. var t = Scalar.Clamp(tx);
  7588. t = -2.0 * t * t * t + 3.0 * t * t;
  7589. return to * t + from * (1.0 - t);
  7590. };
  7591. /**
  7592. * Moves a value current towards target.
  7593. *
  7594. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7595. * Negative values of maxDelta pushes the value away from target.
  7596. */
  7597. Scalar.MoveTowards = function (current, target, maxDelta) {
  7598. var result = 0;
  7599. if (Math.abs(target - current) <= maxDelta) {
  7600. result = target;
  7601. }
  7602. else {
  7603. result = current + Scalar.Sign(target - current) * maxDelta;
  7604. }
  7605. return result;
  7606. };
  7607. /**
  7608. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7609. *
  7610. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7611. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7612. */
  7613. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7614. var num = Scalar.DeltaAngle(current, target);
  7615. var result = 0;
  7616. if (-maxDelta < num && num < maxDelta) {
  7617. result = target;
  7618. }
  7619. else {
  7620. target = current + num;
  7621. result = Scalar.MoveTowards(current, target, maxDelta);
  7622. }
  7623. return result;
  7624. };
  7625. /**
  7626. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7627. */
  7628. Scalar.Lerp = function (start, end, amount) {
  7629. return start + ((end - start) * amount);
  7630. };
  7631. /**
  7632. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7633. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7634. */
  7635. Scalar.LerpAngle = function (start, end, amount) {
  7636. var num = Scalar.Repeat(end - start, 360.0);
  7637. if (num > 180.0) {
  7638. num -= 360.0;
  7639. }
  7640. return start + num * Scalar.Clamp(amount);
  7641. };
  7642. /**
  7643. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7644. */
  7645. Scalar.InverseLerp = function (a, b, value) {
  7646. var result = 0;
  7647. if (a != b) {
  7648. result = Scalar.Clamp((value - a) / (b - a));
  7649. }
  7650. else {
  7651. result = 0.0;
  7652. }
  7653. return result;
  7654. };
  7655. /**
  7656. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7657. */
  7658. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7659. var squared = amount * amount;
  7660. var cubed = amount * squared;
  7661. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7662. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7663. var part3 = (cubed - (2.0 * squared)) + amount;
  7664. var part4 = cubed - squared;
  7665. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7666. };
  7667. /**
  7668. * Returns a random float number between and min and max values
  7669. */
  7670. Scalar.RandomRange = function (min, max) {
  7671. if (min === max)
  7672. return min;
  7673. return ((Math.random() * (max - min)) + min);
  7674. };
  7675. /**
  7676. * This function returns percentage of a number in a given range.
  7677. *
  7678. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7679. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7680. */
  7681. Scalar.RangeToPercent = function (number, min, max) {
  7682. return ((number - min) / (max - min));
  7683. };
  7684. /**
  7685. * This function returns number that corresponds to the percentage in a given range.
  7686. *
  7687. * PercentToRange(0.34,0,100) will return 34.
  7688. */
  7689. Scalar.PercentToRange = function (percent, min, max) {
  7690. return ((max - min) * percent + min);
  7691. };
  7692. /**
  7693. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7694. * @param angle The angle to normalize in radian.
  7695. * @return The converted angle.
  7696. */
  7697. Scalar.NormalizeRadians = function (angle) {
  7698. // More precise but slower version kept for reference.
  7699. // angle = angle % Tools.TwoPi;
  7700. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7701. //if (angle > Math.PI) {
  7702. // angle -= Tools.TwoPi;
  7703. //}
  7704. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7705. return angle;
  7706. };
  7707. /**
  7708. * Two pi constants convenient for computation.
  7709. */
  7710. Scalar.TwoPi = Math.PI * 2;
  7711. return Scalar;
  7712. }());
  7713. BABYLON.Scalar = Scalar;
  7714. })(BABYLON || (BABYLON = {}));
  7715. //# sourceMappingURL=babylon.math.scalar.js.map
  7716. //# sourceMappingURL=babylon.mixins.js.map
  7717. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7718. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7719. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7720. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7721. //# sourceMappingURL=babylon.webgl2.js.map
  7722. var BABYLON;
  7723. (function (BABYLON) {
  7724. var __decoratorInitialStore = {};
  7725. var __mergedStore = {};
  7726. var _copySource = function (creationFunction, source, instanciate) {
  7727. var destination = creationFunction();
  7728. // Tags
  7729. if (BABYLON.Tags) {
  7730. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7731. }
  7732. var classStore = getMergedStore(destination);
  7733. // Properties
  7734. for (var property in classStore) {
  7735. var propertyDescriptor = classStore[property];
  7736. var sourceProperty = source[property];
  7737. var propertyType = propertyDescriptor.type;
  7738. if (sourceProperty !== undefined && sourceProperty !== null) {
  7739. switch (propertyType) {
  7740. case 0: // Value
  7741. case 6: // Mesh reference
  7742. case 11: // Camera reference
  7743. destination[property] = sourceProperty;
  7744. break;
  7745. case 1: // Texture
  7746. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7747. break;
  7748. case 2: // Color3
  7749. case 3: // FresnelParameters
  7750. case 4: // Vector2
  7751. case 5: // Vector3
  7752. case 7: // Color Curves
  7753. case 10: // Quaternion
  7754. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7755. break;
  7756. }
  7757. }
  7758. }
  7759. return destination;
  7760. };
  7761. function getDirectStore(target) {
  7762. var classKey = target.getClassName();
  7763. if (!__decoratorInitialStore[classKey]) {
  7764. __decoratorInitialStore[classKey] = {};
  7765. }
  7766. return __decoratorInitialStore[classKey];
  7767. }
  7768. /**
  7769. * Return the list of properties flagged as serializable
  7770. * @param target: host object
  7771. */
  7772. function getMergedStore(target) {
  7773. var classKey = target.getClassName();
  7774. if (__mergedStore[classKey]) {
  7775. return __mergedStore[classKey];
  7776. }
  7777. __mergedStore[classKey] = {};
  7778. var store = __mergedStore[classKey];
  7779. var currentTarget = target;
  7780. var currentKey = classKey;
  7781. while (currentKey) {
  7782. var initialStore = __decoratorInitialStore[currentKey];
  7783. for (var property in initialStore) {
  7784. store[property] = initialStore[property];
  7785. }
  7786. var parent_1 = void 0;
  7787. var done = false;
  7788. do {
  7789. parent_1 = Object.getPrototypeOf(currentTarget);
  7790. if (!parent_1.getClassName) {
  7791. done = true;
  7792. break;
  7793. }
  7794. if (parent_1.getClassName() !== currentKey) {
  7795. break;
  7796. }
  7797. currentTarget = parent_1;
  7798. } while (parent_1);
  7799. if (done) {
  7800. break;
  7801. }
  7802. currentKey = parent_1.getClassName();
  7803. currentTarget = parent_1;
  7804. }
  7805. return store;
  7806. }
  7807. function generateSerializableMember(type, sourceName) {
  7808. return function (target, propertyKey) {
  7809. var classStore = getDirectStore(target);
  7810. if (!classStore[propertyKey]) {
  7811. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7812. }
  7813. };
  7814. }
  7815. function generateExpandMember(setCallback, targetKey) {
  7816. if (targetKey === void 0) { targetKey = null; }
  7817. return function (target, propertyKey) {
  7818. var key = targetKey || ("_" + propertyKey);
  7819. Object.defineProperty(target, propertyKey, {
  7820. get: function () {
  7821. return this[key];
  7822. },
  7823. set: function (value) {
  7824. if (this[key] === value) {
  7825. return;
  7826. }
  7827. this[key] = value;
  7828. target[setCallback].apply(this);
  7829. },
  7830. enumerable: true,
  7831. configurable: true
  7832. });
  7833. };
  7834. }
  7835. function expandToProperty(callback, targetKey) {
  7836. if (targetKey === void 0) { targetKey = null; }
  7837. return generateExpandMember(callback, targetKey);
  7838. }
  7839. BABYLON.expandToProperty = expandToProperty;
  7840. function serialize(sourceName) {
  7841. return generateSerializableMember(0, sourceName); // value member
  7842. }
  7843. BABYLON.serialize = serialize;
  7844. function serializeAsTexture(sourceName) {
  7845. return generateSerializableMember(1, sourceName); // texture member
  7846. }
  7847. BABYLON.serializeAsTexture = serializeAsTexture;
  7848. function serializeAsColor3(sourceName) {
  7849. return generateSerializableMember(2, sourceName); // color3 member
  7850. }
  7851. BABYLON.serializeAsColor3 = serializeAsColor3;
  7852. function serializeAsFresnelParameters(sourceName) {
  7853. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7854. }
  7855. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7856. function serializeAsVector2(sourceName) {
  7857. return generateSerializableMember(4, sourceName); // vector2 member
  7858. }
  7859. BABYLON.serializeAsVector2 = serializeAsVector2;
  7860. function serializeAsVector3(sourceName) {
  7861. return generateSerializableMember(5, sourceName); // vector3 member
  7862. }
  7863. BABYLON.serializeAsVector3 = serializeAsVector3;
  7864. function serializeAsMeshReference(sourceName) {
  7865. return generateSerializableMember(6, sourceName); // mesh reference member
  7866. }
  7867. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7868. function serializeAsColorCurves(sourceName) {
  7869. return generateSerializableMember(7, sourceName); // color curves
  7870. }
  7871. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7872. function serializeAsColor4(sourceName) {
  7873. return generateSerializableMember(8, sourceName); // color 4
  7874. }
  7875. BABYLON.serializeAsColor4 = serializeAsColor4;
  7876. function serializeAsImageProcessingConfiguration(sourceName) {
  7877. return generateSerializableMember(9, sourceName); // image processing
  7878. }
  7879. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7880. function serializeAsQuaternion(sourceName) {
  7881. return generateSerializableMember(10, sourceName); // quaternion member
  7882. }
  7883. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7884. /**
  7885. * Decorator used to define property that can be serialized as reference to a camera
  7886. * @param sourceName defines the name of the property to decorate
  7887. */
  7888. function serializeAsCameraReference(sourceName) {
  7889. return generateSerializableMember(11, sourceName); // camera reference member
  7890. }
  7891. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7892. var SerializationHelper = /** @class */ (function () {
  7893. function SerializationHelper() {
  7894. }
  7895. SerializationHelper.Serialize = function (entity, serializationObject) {
  7896. if (!serializationObject) {
  7897. serializationObject = {};
  7898. }
  7899. // Tags
  7900. if (BABYLON.Tags) {
  7901. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7902. }
  7903. var serializedProperties = getMergedStore(entity);
  7904. // Properties
  7905. for (var property in serializedProperties) {
  7906. var propertyDescriptor = serializedProperties[property];
  7907. var targetPropertyName = propertyDescriptor.sourceName || property;
  7908. var propertyType = propertyDescriptor.type;
  7909. var sourceProperty = entity[property];
  7910. if (sourceProperty !== undefined && sourceProperty !== null) {
  7911. switch (propertyType) {
  7912. case 0: // Value
  7913. serializationObject[targetPropertyName] = sourceProperty;
  7914. break;
  7915. case 1: // Texture
  7916. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7917. break;
  7918. case 2: // Color3
  7919. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7920. break;
  7921. case 3: // FresnelParameters
  7922. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7923. break;
  7924. case 4: // Vector2
  7925. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7926. break;
  7927. case 5: // Vector3
  7928. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7929. break;
  7930. case 6: // Mesh reference
  7931. serializationObject[targetPropertyName] = sourceProperty.id;
  7932. break;
  7933. case 7: // Color Curves
  7934. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7935. break;
  7936. case 8: // Color 4
  7937. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7938. break;
  7939. case 9: // Image Processing
  7940. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7941. break;
  7942. case 10: // Quaternion
  7943. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7944. break;
  7945. case 11: // Camera reference
  7946. serializationObject[targetPropertyName] = sourceProperty.id;
  7947. break;
  7948. }
  7949. }
  7950. }
  7951. return serializationObject;
  7952. };
  7953. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7954. if (rootUrl === void 0) { rootUrl = null; }
  7955. var destination = creationFunction();
  7956. if (!rootUrl) {
  7957. rootUrl = "";
  7958. }
  7959. // Tags
  7960. if (BABYLON.Tags) {
  7961. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7962. }
  7963. var classStore = getMergedStore(destination);
  7964. // Properties
  7965. for (var property in classStore) {
  7966. var propertyDescriptor = classStore[property];
  7967. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7968. var propertyType = propertyDescriptor.type;
  7969. if (sourceProperty !== undefined && sourceProperty !== null) {
  7970. var dest = destination;
  7971. switch (propertyType) {
  7972. case 0: // Value
  7973. dest[property] = sourceProperty;
  7974. break;
  7975. case 1: // Texture
  7976. if (scene) {
  7977. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7978. }
  7979. break;
  7980. case 2: // Color3
  7981. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7982. break;
  7983. case 3: // FresnelParameters
  7984. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7985. break;
  7986. case 4: // Vector2
  7987. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7988. break;
  7989. case 5: // Vector3
  7990. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7991. break;
  7992. case 6: // Mesh reference
  7993. if (scene) {
  7994. dest[property] = scene.getLastMeshByID(sourceProperty);
  7995. }
  7996. break;
  7997. case 7: // Color Curves
  7998. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7999. break;
  8000. case 8: // Color 4
  8001. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8002. break;
  8003. case 9: // Image Processing
  8004. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8005. break;
  8006. case 10: // Quaternion
  8007. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8008. break;
  8009. case 11: // Camera reference
  8010. if (scene) {
  8011. dest[property] = scene.getCameraByID(sourceProperty);
  8012. }
  8013. break;
  8014. }
  8015. }
  8016. }
  8017. return destination;
  8018. };
  8019. SerializationHelper.Clone = function (creationFunction, source) {
  8020. return _copySource(creationFunction, source, false);
  8021. };
  8022. SerializationHelper.Instanciate = function (creationFunction, source) {
  8023. return _copySource(creationFunction, source, true);
  8024. };
  8025. return SerializationHelper;
  8026. }());
  8027. BABYLON.SerializationHelper = SerializationHelper;
  8028. })(BABYLON || (BABYLON = {}));
  8029. //# sourceMappingURL=babylon.decorators.js.map
  8030. var BABYLON;
  8031. (function (BABYLON) {
  8032. /**
  8033. * Wrapper class for promise with external resolve and reject.
  8034. */
  8035. var Deferred = /** @class */ (function () {
  8036. /**
  8037. * Constructor for this deferred object.
  8038. */
  8039. function Deferred() {
  8040. var _this = this;
  8041. this.promise = new Promise(function (resolve, reject) {
  8042. _this._resolve = resolve;
  8043. _this._reject = reject;
  8044. });
  8045. }
  8046. Object.defineProperty(Deferred.prototype, "resolve", {
  8047. /**
  8048. * The resolve method of the promise associated with this deferred object.
  8049. */
  8050. get: function () {
  8051. return this._resolve;
  8052. },
  8053. enumerable: true,
  8054. configurable: true
  8055. });
  8056. Object.defineProperty(Deferred.prototype, "reject", {
  8057. /**
  8058. * The reject method of the promise associated with this deferred object.
  8059. */
  8060. get: function () {
  8061. return this._reject;
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. return Deferred;
  8067. }());
  8068. BABYLON.Deferred = Deferred;
  8069. })(BABYLON || (BABYLON = {}));
  8070. //# sourceMappingURL=babylon.deferred.js.map
  8071. var BABYLON;
  8072. (function (BABYLON) {
  8073. /**
  8074. * A class serves as a medium between the observable and its observers
  8075. */
  8076. var EventState = /** @class */ (function () {
  8077. /**
  8078. * Create a new EventState
  8079. * @param mask defines the mask associated with this state
  8080. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8081. * @param target defines the original target of the state
  8082. * @param currentTarget defines the current target of the state
  8083. */
  8084. function EventState(mask, skipNextObservers, target, currentTarget) {
  8085. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8086. this.initalize(mask, skipNextObservers, target, currentTarget);
  8087. }
  8088. /**
  8089. * Initialize the current event state
  8090. * @param mask defines the mask associated with this state
  8091. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8092. * @param target defines the original target of the state
  8093. * @param currentTarget defines the current target of the state
  8094. * @returns the current event state
  8095. */
  8096. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8097. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8098. this.mask = mask;
  8099. this.skipNextObservers = skipNextObservers;
  8100. this.target = target;
  8101. this.currentTarget = currentTarget;
  8102. return this;
  8103. };
  8104. return EventState;
  8105. }());
  8106. BABYLON.EventState = EventState;
  8107. /**
  8108. * Represent an Observer registered to a given Observable object.
  8109. */
  8110. var Observer = /** @class */ (function () {
  8111. /**
  8112. * Creates a new observer
  8113. * @param callback defines the callback to call when the observer is notified
  8114. * @param mask defines the mask of the observer (used to filter notifications)
  8115. * @param scope defines the current scope used to restore the JS context
  8116. */
  8117. function Observer(
  8118. /**
  8119. * Defines the callback to call when the observer is notified
  8120. */
  8121. callback,
  8122. /**
  8123. * Defines the mask of the observer (used to filter notifications)
  8124. */
  8125. mask,
  8126. /**
  8127. * Defines the current scope used to restore the JS context
  8128. */
  8129. scope) {
  8130. if (scope === void 0) { scope = null; }
  8131. this.callback = callback;
  8132. this.mask = mask;
  8133. this.scope = scope;
  8134. /** @hidden */
  8135. this._willBeUnregistered = false;
  8136. /**
  8137. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8138. */
  8139. this.unregisterOnNextCall = false;
  8140. }
  8141. return Observer;
  8142. }());
  8143. BABYLON.Observer = Observer;
  8144. /**
  8145. * Represent a list of observers registered to multiple Observables object.
  8146. */
  8147. var MultiObserver = /** @class */ (function () {
  8148. function MultiObserver() {
  8149. }
  8150. /**
  8151. * Release associated resources
  8152. */
  8153. MultiObserver.prototype.dispose = function () {
  8154. if (this._observers && this._observables) {
  8155. for (var index = 0; index < this._observers.length; index++) {
  8156. this._observables[index].remove(this._observers[index]);
  8157. }
  8158. }
  8159. this._observers = null;
  8160. this._observables = null;
  8161. };
  8162. /**
  8163. * Raise a callback when one of the observable will notify
  8164. * @param observables defines a list of observables to watch
  8165. * @param callback defines the callback to call on notification
  8166. * @param mask defines the mask used to filter notifications
  8167. * @param scope defines the current scope used to restore the JS context
  8168. * @returns the new MultiObserver
  8169. */
  8170. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8171. if (mask === void 0) { mask = -1; }
  8172. if (scope === void 0) { scope = null; }
  8173. var result = new MultiObserver();
  8174. result._observers = new Array();
  8175. result._observables = observables;
  8176. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8177. var observable = observables_1[_i];
  8178. var observer = observable.add(callback, mask, false, scope);
  8179. if (observer) {
  8180. result._observers.push(observer);
  8181. }
  8182. }
  8183. return result;
  8184. };
  8185. return MultiObserver;
  8186. }());
  8187. BABYLON.MultiObserver = MultiObserver;
  8188. /**
  8189. * The Observable class is a simple implementation of the Observable pattern.
  8190. *
  8191. * 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.
  8192. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8193. * 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).
  8194. * 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.
  8195. */
  8196. var Observable = /** @class */ (function () {
  8197. /**
  8198. * Creates a new observable
  8199. * @param onObserverAdded defines a callback to call when a new observer is added
  8200. */
  8201. function Observable(onObserverAdded) {
  8202. this._observers = new Array();
  8203. this._eventState = new EventState(0);
  8204. if (onObserverAdded) {
  8205. this._onObserverAdded = onObserverAdded;
  8206. }
  8207. }
  8208. /**
  8209. * Create a new Observer with the specified callback
  8210. * @param callback the callback that will be executed for that Observer
  8211. * @param mask the mask used to filter observers
  8212. * @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.
  8213. * @param scope optional scope for the callback to be called from
  8214. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8215. * @returns the new observer created for the callback
  8216. */
  8217. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8218. if (mask === void 0) { mask = -1; }
  8219. if (insertFirst === void 0) { insertFirst = false; }
  8220. if (scope === void 0) { scope = null; }
  8221. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8222. if (!callback) {
  8223. return null;
  8224. }
  8225. var observer = new Observer(callback, mask, scope);
  8226. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8227. if (insertFirst) {
  8228. this._observers.unshift(observer);
  8229. }
  8230. else {
  8231. this._observers.push(observer);
  8232. }
  8233. if (this._onObserverAdded) {
  8234. this._onObserverAdded(observer);
  8235. }
  8236. return observer;
  8237. };
  8238. /**
  8239. * Create a new Observer with the specified callback and unregisters after the next notification
  8240. * @param callback the callback that will be executed for that Observer
  8241. * @returns the new observer created for the callback
  8242. */
  8243. Observable.prototype.addOnce = function (callback) {
  8244. return this.add(callback, undefined, undefined, undefined, true);
  8245. };
  8246. /**
  8247. * Remove an Observer from the Observable object
  8248. * @param observer the instance of the Observer to remove
  8249. * @returns false if it doesn't belong to this Observable
  8250. */
  8251. Observable.prototype.remove = function (observer) {
  8252. if (!observer) {
  8253. return false;
  8254. }
  8255. var index = this._observers.indexOf(observer);
  8256. if (index !== -1) {
  8257. this._deferUnregister(observer);
  8258. return true;
  8259. }
  8260. return false;
  8261. };
  8262. /**
  8263. * Remove a callback from the Observable object
  8264. * @param callback the callback to remove
  8265. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8266. * @returns false if it doesn't belong to this Observable
  8267. */
  8268. Observable.prototype.removeCallback = function (callback, scope) {
  8269. for (var index = 0; index < this._observers.length; index++) {
  8270. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8271. this._deferUnregister(this._observers[index]);
  8272. return true;
  8273. }
  8274. }
  8275. return false;
  8276. };
  8277. Observable.prototype._deferUnregister = function (observer) {
  8278. var _this = this;
  8279. observer.unregisterOnNextCall = false;
  8280. observer._willBeUnregistered = true;
  8281. BABYLON.Tools.SetImmediate(function () {
  8282. _this._remove(observer);
  8283. });
  8284. };
  8285. // This should only be called when not iterating over _observers to avoid callback skipping.
  8286. // Removes an observer from the _observer Array.
  8287. Observable.prototype._remove = function (observer) {
  8288. if (!observer) {
  8289. return false;
  8290. }
  8291. var index = this._observers.indexOf(observer);
  8292. if (index !== -1) {
  8293. this._observers.splice(index, 1);
  8294. return true;
  8295. }
  8296. return false;
  8297. };
  8298. /**
  8299. * Notify all Observers by calling their respective callback with the given data
  8300. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8301. * @param eventData defines the data to send to all observers
  8302. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8303. * @param target defines the original target of the state
  8304. * @param currentTarget defines the current target of the state
  8305. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8306. */
  8307. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8308. if (mask === void 0) { mask = -1; }
  8309. if (!this._observers.length) {
  8310. return true;
  8311. }
  8312. var state = this._eventState;
  8313. state.mask = mask;
  8314. state.target = target;
  8315. state.currentTarget = currentTarget;
  8316. state.skipNextObservers = false;
  8317. state.lastReturnValue = eventData;
  8318. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8319. var obs = _a[_i];
  8320. if (obs._willBeUnregistered) {
  8321. continue;
  8322. }
  8323. if (obs.mask & mask) {
  8324. if (obs.scope) {
  8325. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8326. }
  8327. else {
  8328. state.lastReturnValue = obs.callback(eventData, state);
  8329. }
  8330. if (obs.unregisterOnNextCall) {
  8331. this._deferUnregister(obs);
  8332. }
  8333. }
  8334. if (state.skipNextObservers) {
  8335. return false;
  8336. }
  8337. }
  8338. return true;
  8339. };
  8340. /**
  8341. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8342. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8343. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8344. * and it is crucial that all callbacks will be executed.
  8345. * The order of the callbacks is kept, callbacks are not executed parallel.
  8346. *
  8347. * @param eventData The data to be sent to each callback
  8348. * @param mask is used to filter observers defaults to -1
  8349. * @param target defines the callback target (see EventState)
  8350. * @param currentTarget defines he current object in the bubbling phase
  8351. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8352. */
  8353. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8354. var _this = this;
  8355. if (mask === void 0) { mask = -1; }
  8356. // create an empty promise
  8357. var p = Promise.resolve(eventData);
  8358. // no observers? return this promise.
  8359. if (!this._observers.length) {
  8360. return p;
  8361. }
  8362. var state = this._eventState;
  8363. state.mask = mask;
  8364. state.target = target;
  8365. state.currentTarget = currentTarget;
  8366. state.skipNextObservers = false;
  8367. // execute one callback after another (not using Promise.all, the order is important)
  8368. this._observers.forEach(function (obs) {
  8369. if (state.skipNextObservers) {
  8370. return;
  8371. }
  8372. if (obs._willBeUnregistered) {
  8373. return;
  8374. }
  8375. if (obs.mask & mask) {
  8376. if (obs.scope) {
  8377. p = p.then(function (lastReturnedValue) {
  8378. state.lastReturnValue = lastReturnedValue;
  8379. return obs.callback.apply(obs.scope, [eventData, state]);
  8380. });
  8381. }
  8382. else {
  8383. p = p.then(function (lastReturnedValue) {
  8384. state.lastReturnValue = lastReturnedValue;
  8385. return obs.callback(eventData, state);
  8386. });
  8387. }
  8388. if (obs.unregisterOnNextCall) {
  8389. _this._deferUnregister(obs);
  8390. }
  8391. }
  8392. });
  8393. // return the eventData
  8394. return p.then(function () { return eventData; });
  8395. };
  8396. /**
  8397. * Notify a specific observer
  8398. * @param observer defines the observer to notify
  8399. * @param eventData defines the data to be sent to each callback
  8400. * @param mask is used to filter observers defaults to -1
  8401. */
  8402. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8403. if (mask === void 0) { mask = -1; }
  8404. var state = this._eventState;
  8405. state.mask = mask;
  8406. state.skipNextObservers = false;
  8407. observer.callback(eventData, state);
  8408. };
  8409. /**
  8410. * Gets a boolean indicating if the observable has at least one observer
  8411. * @returns true is the Observable has at least one Observer registered
  8412. */
  8413. Observable.prototype.hasObservers = function () {
  8414. return this._observers.length > 0;
  8415. };
  8416. /**
  8417. * Clear the list of observers
  8418. */
  8419. Observable.prototype.clear = function () {
  8420. this._observers = new Array();
  8421. this._onObserverAdded = null;
  8422. };
  8423. /**
  8424. * Clone the current observable
  8425. * @returns a new observable
  8426. */
  8427. Observable.prototype.clone = function () {
  8428. var result = new Observable();
  8429. result._observers = this._observers.slice(0);
  8430. return result;
  8431. };
  8432. /**
  8433. * Does this observable handles observer registered with a given mask
  8434. * @param mask defines the mask to be tested
  8435. * @return whether or not one observer registered with the given mask is handeled
  8436. **/
  8437. Observable.prototype.hasSpecificMask = function (mask) {
  8438. if (mask === void 0) { mask = -1; }
  8439. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8440. var obs = _a[_i];
  8441. if (obs.mask & mask || obs.mask === mask) {
  8442. return true;
  8443. }
  8444. }
  8445. return false;
  8446. };
  8447. return Observable;
  8448. }());
  8449. BABYLON.Observable = Observable;
  8450. })(BABYLON || (BABYLON = {}));
  8451. //# sourceMappingURL=babylon.observable.js.map
  8452. var BABYLON;
  8453. (function (BABYLON) {
  8454. var SmartArray = /** @class */ (function () {
  8455. function SmartArray(capacity) {
  8456. this.length = 0;
  8457. this.data = new Array(capacity);
  8458. this._id = SmartArray._GlobalId++;
  8459. }
  8460. SmartArray.prototype.push = function (value) {
  8461. this.data[this.length++] = value;
  8462. if (this.length > this.data.length) {
  8463. this.data.length *= 2;
  8464. }
  8465. };
  8466. SmartArray.prototype.forEach = function (func) {
  8467. for (var index = 0; index < this.length; index++) {
  8468. func(this.data[index]);
  8469. }
  8470. };
  8471. SmartArray.prototype.sort = function (compareFn) {
  8472. this.data.sort(compareFn);
  8473. };
  8474. SmartArray.prototype.reset = function () {
  8475. this.length = 0;
  8476. };
  8477. SmartArray.prototype.dispose = function () {
  8478. this.reset();
  8479. if (this.data) {
  8480. this.data.length = 0;
  8481. this.data = [];
  8482. }
  8483. };
  8484. SmartArray.prototype.concat = function (array) {
  8485. if (array.length === 0) {
  8486. return;
  8487. }
  8488. if (this.length + array.length > this.data.length) {
  8489. this.data.length = (this.length + array.length) * 2;
  8490. }
  8491. for (var index = 0; index < array.length; index++) {
  8492. this.data[this.length++] = (array.data || array)[index];
  8493. }
  8494. };
  8495. SmartArray.prototype.indexOf = function (value) {
  8496. var position = this.data.indexOf(value);
  8497. if (position >= this.length) {
  8498. return -1;
  8499. }
  8500. return position;
  8501. };
  8502. SmartArray.prototype.contains = function (value) {
  8503. return this.data.indexOf(value) !== -1;
  8504. };
  8505. // Statics
  8506. SmartArray._GlobalId = 0;
  8507. return SmartArray;
  8508. }());
  8509. BABYLON.SmartArray = SmartArray;
  8510. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8511. __extends(SmartArrayNoDuplicate, _super);
  8512. function SmartArrayNoDuplicate() {
  8513. var _this = _super !== null && _super.apply(this, arguments) || this;
  8514. _this._duplicateId = 0;
  8515. return _this;
  8516. }
  8517. SmartArrayNoDuplicate.prototype.push = function (value) {
  8518. _super.prototype.push.call(this, value);
  8519. if (!value.__smartArrayFlags) {
  8520. value.__smartArrayFlags = {};
  8521. }
  8522. value.__smartArrayFlags[this._id] = this._duplicateId;
  8523. };
  8524. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8525. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8526. return false;
  8527. }
  8528. this.push(value);
  8529. return true;
  8530. };
  8531. SmartArrayNoDuplicate.prototype.reset = function () {
  8532. _super.prototype.reset.call(this);
  8533. this._duplicateId++;
  8534. };
  8535. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8536. if (array.length === 0) {
  8537. return;
  8538. }
  8539. if (this.length + array.length > this.data.length) {
  8540. this.data.length = (this.length + array.length) * 2;
  8541. }
  8542. for (var index = 0; index < array.length; index++) {
  8543. var item = (array.data || array)[index];
  8544. this.pushNoDuplicate(item);
  8545. }
  8546. };
  8547. return SmartArrayNoDuplicate;
  8548. }(SmartArray));
  8549. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8550. })(BABYLON || (BABYLON = {}));
  8551. //# sourceMappingURL=babylon.smartArray.js.map
  8552. var BABYLON;
  8553. (function (BABYLON) {
  8554. /** Class used to store color gradient */
  8555. var ColorGradient = /** @class */ (function () {
  8556. function ColorGradient() {
  8557. }
  8558. /**
  8559. * Will get a color picked randomly between color1 and color2.
  8560. * If color2 is undefined then color1 will be used
  8561. * @param result defines the target Color4 to store the result in
  8562. */
  8563. ColorGradient.prototype.getColorToRef = function (result) {
  8564. if (!this.color2) {
  8565. result.copyFrom(this.color1);
  8566. return;
  8567. }
  8568. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8569. };
  8570. return ColorGradient;
  8571. }());
  8572. BABYLON.ColorGradient = ColorGradient;
  8573. /** Class used to store factor gradient */
  8574. var FactorGradient = /** @class */ (function () {
  8575. function FactorGradient() {
  8576. }
  8577. /**
  8578. * Will get a number picked randomly between factor1 and factor2.
  8579. * If factor2 is undefined then factor1 will be used
  8580. * @returns the picked number
  8581. */
  8582. FactorGradient.prototype.getFactor = function () {
  8583. if (this.factor2 === undefined) {
  8584. return this.factor1;
  8585. }
  8586. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8587. };
  8588. return FactorGradient;
  8589. }());
  8590. BABYLON.FactorGradient = FactorGradient;
  8591. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8592. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8593. var LoadFileError = /** @class */ (function (_super) {
  8594. __extends(LoadFileError, _super);
  8595. function LoadFileError(message, request) {
  8596. var _this = _super.call(this, message) || this;
  8597. _this.request = request;
  8598. _this.name = "LoadFileError";
  8599. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8600. return _this;
  8601. }
  8602. // Polyfill for Object.setPrototypeOf if necessary.
  8603. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8604. return LoadFileError;
  8605. }(Error));
  8606. BABYLON.LoadFileError = LoadFileError;
  8607. var RetryStrategy = /** @class */ (function () {
  8608. function RetryStrategy() {
  8609. }
  8610. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8611. if (maxRetries === void 0) { maxRetries = 3; }
  8612. if (baseInterval === void 0) { baseInterval = 500; }
  8613. return function (url, request, retryIndex) {
  8614. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8615. return -1;
  8616. }
  8617. return Math.pow(2, retryIndex) * baseInterval;
  8618. };
  8619. };
  8620. return RetryStrategy;
  8621. }());
  8622. BABYLON.RetryStrategy = RetryStrategy;
  8623. // Screenshots
  8624. var screenshotCanvas;
  8625. var cloneValue = function (source, destinationObject) {
  8626. if (!source)
  8627. return null;
  8628. if (source instanceof BABYLON.Mesh) {
  8629. return null;
  8630. }
  8631. if (source instanceof BABYLON.SubMesh) {
  8632. return source.clone(destinationObject);
  8633. }
  8634. else if (source.clone) {
  8635. return source.clone();
  8636. }
  8637. return null;
  8638. };
  8639. var Tools = /** @class */ (function () {
  8640. function Tools() {
  8641. }
  8642. /**
  8643. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8644. * @param u defines the coordinate on X axis
  8645. * @param v defines the coordinate on Y axis
  8646. * @param width defines the width of the source data
  8647. * @param height defines the height of the source data
  8648. * @param pixels defines the source byte array
  8649. * @param color defines the output color
  8650. */
  8651. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8652. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8653. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8654. var position = (wrappedU + wrappedV * width) * 4;
  8655. color.r = pixels[position] / 255;
  8656. color.g = pixels[position + 1] / 255;
  8657. color.b = pixels[position + 2] / 255;
  8658. color.a = pixels[position + 3] / 255;
  8659. };
  8660. /**
  8661. * Interpolates between a and b via alpha
  8662. * @param a The lower value (returned when alpha = 0)
  8663. * @param b The upper value (returned when alpha = 1)
  8664. * @param alpha The interpolation-factor
  8665. * @return The mixed value
  8666. */
  8667. Tools.Mix = function (a, b, alpha) {
  8668. return a * (1 - alpha) + b * alpha;
  8669. };
  8670. Tools.Instantiate = function (className) {
  8671. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8672. return Tools.RegisteredExternalClasses[className];
  8673. }
  8674. var arr = className.split(".");
  8675. var fn = (window || this);
  8676. for (var i = 0, len = arr.length; i < len; i++) {
  8677. fn = fn[arr[i]];
  8678. }
  8679. if (typeof fn !== "function") {
  8680. return null;
  8681. }
  8682. return fn;
  8683. };
  8684. /**
  8685. * Provides a slice function that will work even on IE
  8686. * @param data defines the array to slice
  8687. * @param start defines the start of the data (optional)
  8688. * @param end defines the end of the data (optional)
  8689. * @returns the new sliced array
  8690. */
  8691. Tools.Slice = function (data, start, end) {
  8692. if (data.slice) {
  8693. return data.slice(start, end);
  8694. }
  8695. return Array.prototype.slice.call(data, start, end);
  8696. };
  8697. Tools.SetImmediate = function (action) {
  8698. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8699. window.setImmediate(action);
  8700. }
  8701. else {
  8702. setTimeout(action, 1);
  8703. }
  8704. };
  8705. Tools.IsExponentOfTwo = function (value) {
  8706. var count = 1;
  8707. do {
  8708. count *= 2;
  8709. } while (count < value);
  8710. return count === value;
  8711. };
  8712. /**
  8713. * Returns the nearest 32-bit single precision float representation of a Number
  8714. * @param value A Number. If the parameter is of a different type, it will get converted
  8715. * to a number or to NaN if it cannot be converted
  8716. * @returns number
  8717. */
  8718. Tools.FloatRound = function (value) {
  8719. if (Math.fround) {
  8720. return Math.fround(value);
  8721. }
  8722. return (Tools._tmpFloatArray[0] = value);
  8723. };
  8724. /**
  8725. * Find the next highest power of two.
  8726. * @param x Number to start search from.
  8727. * @return Next highest power of two.
  8728. */
  8729. Tools.CeilingPOT = function (x) {
  8730. x--;
  8731. x |= x >> 1;
  8732. x |= x >> 2;
  8733. x |= x >> 4;
  8734. x |= x >> 8;
  8735. x |= x >> 16;
  8736. x++;
  8737. return x;
  8738. };
  8739. /**
  8740. * Find the next lowest power of two.
  8741. * @param x Number to start search from.
  8742. * @return Next lowest power of two.
  8743. */
  8744. Tools.FloorPOT = function (x) {
  8745. x = x | (x >> 1);
  8746. x = x | (x >> 2);
  8747. x = x | (x >> 4);
  8748. x = x | (x >> 8);
  8749. x = x | (x >> 16);
  8750. return x - (x >> 1);
  8751. };
  8752. /**
  8753. * Find the nearest power of two.
  8754. * @param x Number to start search from.
  8755. * @return Next nearest power of two.
  8756. */
  8757. Tools.NearestPOT = function (x) {
  8758. var c = Tools.CeilingPOT(x);
  8759. var f = Tools.FloorPOT(x);
  8760. return (c - x) > (x - f) ? f : c;
  8761. };
  8762. Tools.GetExponentOfTwo = function (value, max, mode) {
  8763. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8764. var pot;
  8765. switch (mode) {
  8766. case BABYLON.Engine.SCALEMODE_FLOOR:
  8767. pot = Tools.FloorPOT(value);
  8768. break;
  8769. case BABYLON.Engine.SCALEMODE_NEAREST:
  8770. pot = Tools.NearestPOT(value);
  8771. break;
  8772. case BABYLON.Engine.SCALEMODE_CEILING:
  8773. default:
  8774. pot = Tools.CeilingPOT(value);
  8775. break;
  8776. }
  8777. return Math.min(pot, max);
  8778. };
  8779. Tools.GetFilename = function (path) {
  8780. var index = path.lastIndexOf("/");
  8781. if (index < 0)
  8782. return path;
  8783. return path.substring(index + 1);
  8784. };
  8785. /**
  8786. * Extracts the "folder" part of a path (everything before the filename).
  8787. * @param uri The URI to extract the info from
  8788. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8789. * @returns The "folder" part of the path
  8790. */
  8791. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8792. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8793. var index = uri.lastIndexOf("/");
  8794. if (index < 0) {
  8795. if (returnUnchangedIfNoSlash) {
  8796. return uri;
  8797. }
  8798. return "";
  8799. }
  8800. return uri.substring(0, index + 1);
  8801. };
  8802. Tools.GetDOMTextContent = function (element) {
  8803. var result = "";
  8804. var child = element.firstChild;
  8805. while (child) {
  8806. if (child.nodeType === 3) {
  8807. result += child.textContent;
  8808. }
  8809. child = child.nextSibling;
  8810. }
  8811. return result;
  8812. };
  8813. Tools.ToDegrees = function (angle) {
  8814. return angle * 180 / Math.PI;
  8815. };
  8816. Tools.ToRadians = function (angle) {
  8817. return angle * Math.PI / 180;
  8818. };
  8819. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8820. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8821. var output = "";
  8822. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8823. var i = 0;
  8824. var bytes = new Uint8Array(buffer);
  8825. while (i < bytes.length) {
  8826. chr1 = bytes[i++];
  8827. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8828. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8829. enc1 = chr1 >> 2;
  8830. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8831. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8832. enc4 = chr3 & 63;
  8833. if (isNaN(chr2)) {
  8834. enc3 = enc4 = 64;
  8835. }
  8836. else if (isNaN(chr3)) {
  8837. enc4 = 64;
  8838. }
  8839. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8840. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8841. }
  8842. return "data:image/png;base64," + output;
  8843. };
  8844. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8845. if (bias === void 0) { bias = null; }
  8846. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8847. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8848. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8849. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8850. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8851. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8852. }
  8853. if (bias) {
  8854. minimum.x -= minimum.x * bias.x + bias.y;
  8855. minimum.y -= minimum.y * bias.x + bias.y;
  8856. minimum.z -= minimum.z * bias.x + bias.y;
  8857. maximum.x += maximum.x * bias.x + bias.y;
  8858. maximum.y += maximum.y * bias.x + bias.y;
  8859. maximum.z += maximum.z * bias.x + bias.y;
  8860. }
  8861. return {
  8862. minimum: minimum,
  8863. maximum: maximum
  8864. };
  8865. };
  8866. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8867. if (bias === void 0) { bias = null; }
  8868. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8869. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8870. if (!stride) {
  8871. stride = 3;
  8872. }
  8873. for (var index = start; index < start + count; index++) {
  8874. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8875. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8876. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8877. }
  8878. if (bias) {
  8879. minimum.x -= minimum.x * bias.x + bias.y;
  8880. minimum.y -= minimum.y * bias.x + bias.y;
  8881. minimum.z -= minimum.z * bias.x + bias.y;
  8882. maximum.x += maximum.x * bias.x + bias.y;
  8883. maximum.y += maximum.y * bias.x + bias.y;
  8884. maximum.z += maximum.z * bias.x + bias.y;
  8885. }
  8886. return {
  8887. minimum: minimum,
  8888. maximum: maximum
  8889. };
  8890. };
  8891. Tools.Vector2ArrayFeeder = function (array) {
  8892. return function (index) {
  8893. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8894. var length = isFloatArray ? array.length / 2 : array.length;
  8895. if (index >= length) {
  8896. return null;
  8897. }
  8898. if (isFloatArray) {
  8899. var fa = array;
  8900. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8901. }
  8902. var a = array;
  8903. return a[index];
  8904. };
  8905. };
  8906. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8907. if (bias === void 0) { bias = null; }
  8908. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8909. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8910. var i = 0;
  8911. var cur = feeder(i++);
  8912. while (cur) {
  8913. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8914. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8915. cur = feeder(i++);
  8916. }
  8917. if (bias) {
  8918. minimum.x -= minimum.x * bias.x + bias.y;
  8919. minimum.y -= minimum.y * bias.x + bias.y;
  8920. maximum.x += maximum.x * bias.x + bias.y;
  8921. maximum.y += maximum.y * bias.x + bias.y;
  8922. }
  8923. return {
  8924. minimum: minimum,
  8925. maximum: maximum
  8926. };
  8927. };
  8928. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8929. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8930. return null;
  8931. return Array.isArray(obj) ? obj : [obj];
  8932. };
  8933. // Misc.
  8934. Tools.GetPointerPrefix = function () {
  8935. var eventPrefix = "pointer";
  8936. // Check if pointer events are supported
  8937. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8938. eventPrefix = "mouse";
  8939. }
  8940. return eventPrefix;
  8941. };
  8942. /**
  8943. * @param func - the function to be called
  8944. * @param requester - the object that will request the next frame. Falls back to window.
  8945. */
  8946. Tools.QueueNewFrame = function (func, requester) {
  8947. if (!Tools.IsWindowObjectExist()) {
  8948. return setTimeout(func, 16);
  8949. }
  8950. if (!requester) {
  8951. requester = window;
  8952. }
  8953. if (requester.requestAnimationFrame) {
  8954. return requester.requestAnimationFrame(func);
  8955. }
  8956. else if (requester.msRequestAnimationFrame) {
  8957. return requester.msRequestAnimationFrame(func);
  8958. }
  8959. else if (requester.webkitRequestAnimationFrame) {
  8960. return requester.webkitRequestAnimationFrame(func);
  8961. }
  8962. else if (requester.mozRequestAnimationFrame) {
  8963. return requester.mozRequestAnimationFrame(func);
  8964. }
  8965. else if (requester.oRequestAnimationFrame) {
  8966. return requester.oRequestAnimationFrame(func);
  8967. }
  8968. else {
  8969. return window.setTimeout(func, 16);
  8970. }
  8971. };
  8972. Tools.RequestFullscreen = function (element) {
  8973. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8974. if (!requestFunction)
  8975. return;
  8976. requestFunction.call(element);
  8977. };
  8978. Tools.ExitFullscreen = function () {
  8979. if (document.exitFullscreen) {
  8980. document.exitFullscreen();
  8981. }
  8982. else if (document.mozCancelFullScreen) {
  8983. document.mozCancelFullScreen();
  8984. }
  8985. else if (document.webkitCancelFullScreen) {
  8986. document.webkitCancelFullScreen();
  8987. }
  8988. else if (document.msCancelFullScreen) {
  8989. document.msCancelFullScreen();
  8990. }
  8991. };
  8992. Tools.SetCorsBehavior = function (url, element) {
  8993. if (url && url.indexOf("data:") === 0) {
  8994. return;
  8995. }
  8996. if (Tools.CorsBehavior) {
  8997. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8998. element.crossOrigin = Tools.CorsBehavior;
  8999. }
  9000. else {
  9001. var result = Tools.CorsBehavior(url);
  9002. if (result) {
  9003. element.crossOrigin = result;
  9004. }
  9005. }
  9006. }
  9007. };
  9008. // External files
  9009. Tools.CleanUrl = function (url) {
  9010. url = url.replace(/#/mg, "%23");
  9011. return url;
  9012. };
  9013. /**
  9014. * Loads an image as an HTMLImageElement.
  9015. * @param input url string, ArrayBuffer, or Blob to load
  9016. * @param onLoad callback called when the image successfully loads
  9017. * @param onError callback called when the image fails to load
  9018. * @param database database for caching
  9019. * @returns the HTMLImageElement of the loaded image
  9020. */
  9021. Tools.LoadImage = function (input, onLoad, onError, database) {
  9022. var url;
  9023. var usingObjectURL = false;
  9024. if (input instanceof ArrayBuffer) {
  9025. url = URL.createObjectURL(new Blob([input]));
  9026. usingObjectURL = true;
  9027. }
  9028. else if (input instanceof Blob) {
  9029. url = URL.createObjectURL(input);
  9030. usingObjectURL = true;
  9031. }
  9032. else {
  9033. url = Tools.CleanUrl(input);
  9034. url = Tools.PreprocessUrl(input);
  9035. }
  9036. var img = new Image();
  9037. Tools.SetCorsBehavior(url, img);
  9038. var loadHandler = function () {
  9039. if (usingObjectURL && img.src) {
  9040. URL.revokeObjectURL(img.src);
  9041. }
  9042. img.removeEventListener("load", loadHandler);
  9043. img.removeEventListener("error", errorHandler);
  9044. onLoad(img);
  9045. };
  9046. var errorHandler = function (err) {
  9047. if (usingObjectURL && img.src) {
  9048. URL.revokeObjectURL(img.src);
  9049. }
  9050. img.removeEventListener("load", loadHandler);
  9051. img.removeEventListener("error", errorHandler);
  9052. Tools.Error("Error while trying to load image: " + input);
  9053. if (onError) {
  9054. onError("Error while trying to load image: " + input, err);
  9055. }
  9056. };
  9057. img.addEventListener("load", loadHandler);
  9058. img.addEventListener("error", errorHandler);
  9059. var noIndexedDB = function () {
  9060. img.src = url;
  9061. };
  9062. var loadFromIndexedDB = function () {
  9063. if (database) {
  9064. database.loadImageFromDB(url, img);
  9065. }
  9066. };
  9067. //ANY database to do!
  9068. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9069. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9070. }
  9071. else {
  9072. if (url.indexOf("file:") !== -1) {
  9073. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9074. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9075. try {
  9076. var blobURL;
  9077. try {
  9078. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9079. }
  9080. catch (ex) {
  9081. // Chrome doesn't support oneTimeOnly parameter
  9082. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9083. }
  9084. img.src = blobURL;
  9085. usingObjectURL = true;
  9086. }
  9087. catch (e) {
  9088. img.src = "";
  9089. }
  9090. return img;
  9091. }
  9092. }
  9093. noIndexedDB();
  9094. }
  9095. return img;
  9096. };
  9097. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9098. url = Tools.CleanUrl(url);
  9099. url = Tools.PreprocessUrl(url);
  9100. // If file and file input are set
  9101. if (url.indexOf("file:") !== -1) {
  9102. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9103. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9104. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9105. }
  9106. }
  9107. var loadUrl = Tools.BaseUrl + url;
  9108. var aborted = false;
  9109. var fileRequest = {
  9110. onCompleteObservable: new BABYLON.Observable(),
  9111. abort: function () { return aborted = true; },
  9112. };
  9113. var requestFile = function () {
  9114. var request = new XMLHttpRequest();
  9115. var retryHandle = null;
  9116. fileRequest.abort = function () {
  9117. aborted = true;
  9118. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9119. request.abort();
  9120. }
  9121. if (retryHandle !== null) {
  9122. clearTimeout(retryHandle);
  9123. retryHandle = null;
  9124. }
  9125. };
  9126. var retryLoop = function (retryIndex) {
  9127. request.open('GET', loadUrl, true);
  9128. if (useArrayBuffer) {
  9129. request.responseType = "arraybuffer";
  9130. }
  9131. if (onProgress) {
  9132. request.addEventListener("progress", onProgress);
  9133. }
  9134. var onLoadEnd = function () {
  9135. request.removeEventListener("loadend", onLoadEnd);
  9136. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9137. fileRequest.onCompleteObservable.clear();
  9138. };
  9139. request.addEventListener("loadend", onLoadEnd);
  9140. var onReadyStateChange = function () {
  9141. if (aborted) {
  9142. return;
  9143. }
  9144. // In case of undefined state in some browsers.
  9145. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9146. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9147. request.removeEventListener("readystatechange", onReadyStateChange);
  9148. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9149. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9150. return;
  9151. }
  9152. var retryStrategy = Tools.DefaultRetryStrategy;
  9153. if (retryStrategy) {
  9154. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9155. if (waitTime !== -1) {
  9156. // Prevent the request from completing for retry.
  9157. request.removeEventListener("loadend", onLoadEnd);
  9158. request = new XMLHttpRequest();
  9159. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9160. return;
  9161. }
  9162. }
  9163. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9164. if (onError) {
  9165. onError(request, e);
  9166. }
  9167. else {
  9168. throw e;
  9169. }
  9170. }
  9171. };
  9172. request.addEventListener("readystatechange", onReadyStateChange);
  9173. request.send();
  9174. };
  9175. retryLoop(0);
  9176. };
  9177. // Caching all files
  9178. if (database && database.enableSceneOffline) {
  9179. var noIndexedDB_1 = function (request) {
  9180. if (request && request.status > 400) {
  9181. if (onError) {
  9182. onError(request);
  9183. }
  9184. }
  9185. else {
  9186. if (!aborted) {
  9187. requestFile();
  9188. }
  9189. }
  9190. };
  9191. var loadFromIndexedDB = function () {
  9192. // TODO: database needs to support aborting and should return a IFileRequest
  9193. if (aborted) {
  9194. return;
  9195. }
  9196. if (database) {
  9197. database.loadFileFromDB(url, function (data) {
  9198. if (!aborted) {
  9199. onSuccess(data);
  9200. }
  9201. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9202. }, onProgress ? function (event) {
  9203. if (!aborted) {
  9204. onProgress(event);
  9205. }
  9206. } : undefined, noIndexedDB_1, useArrayBuffer);
  9207. }
  9208. };
  9209. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9210. }
  9211. else {
  9212. requestFile();
  9213. }
  9214. return fileRequest;
  9215. };
  9216. /**
  9217. * Load a script (identified by an url). When the url returns, the
  9218. * content of this file is added into a new script element, attached to the DOM (body element)
  9219. */
  9220. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9221. var head = document.getElementsByTagName('head')[0];
  9222. var script = document.createElement('script');
  9223. script.type = 'text/javascript';
  9224. script.src = scriptUrl;
  9225. script.onload = function () {
  9226. if (onSuccess) {
  9227. onSuccess();
  9228. }
  9229. };
  9230. script.onerror = function (e) {
  9231. if (onError) {
  9232. onError("Unable to load script '" + scriptUrl + "'", e);
  9233. }
  9234. };
  9235. head.appendChild(script);
  9236. };
  9237. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9238. var reader = new FileReader();
  9239. var request = {
  9240. onCompleteObservable: new BABYLON.Observable(),
  9241. abort: function () { return reader.abort(); },
  9242. };
  9243. reader.onloadend = function (e) {
  9244. request.onCompleteObservable.notifyObservers(request);
  9245. };
  9246. reader.onload = function (e) {
  9247. //target doesn't have result from ts 1.3
  9248. callback(e.target['result']);
  9249. };
  9250. reader.onprogress = progressCallback;
  9251. reader.readAsDataURL(fileToLoad);
  9252. return request;
  9253. };
  9254. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9255. var reader = new FileReader();
  9256. var request = {
  9257. onCompleteObservable: new BABYLON.Observable(),
  9258. abort: function () { return reader.abort(); },
  9259. };
  9260. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9261. reader.onerror = function (e) {
  9262. Tools.Log("Error while reading file: " + fileToLoad.name);
  9263. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9264. };
  9265. reader.onload = function (e) {
  9266. //target doesn't have result from ts 1.3
  9267. callback(e.target['result']);
  9268. };
  9269. if (progressCallBack) {
  9270. reader.onprogress = progressCallBack;
  9271. }
  9272. if (!useArrayBuffer) {
  9273. // Asynchronous read
  9274. reader.readAsText(fileToLoad);
  9275. }
  9276. else {
  9277. reader.readAsArrayBuffer(fileToLoad);
  9278. }
  9279. return request;
  9280. };
  9281. //returns a downloadable url to a file content.
  9282. Tools.FileAsURL = function (content) {
  9283. var fileBlob = new Blob([content]);
  9284. var url = window.URL || window.webkitURL;
  9285. var link = url.createObjectURL(fileBlob);
  9286. return link;
  9287. };
  9288. // Misc.
  9289. Tools.Format = function (value, decimals) {
  9290. if (decimals === void 0) { decimals = 2; }
  9291. return value.toFixed(decimals);
  9292. };
  9293. Tools.CheckExtends = function (v, min, max) {
  9294. if (v.x < min.x)
  9295. min.x = v.x;
  9296. if (v.y < min.y)
  9297. min.y = v.y;
  9298. if (v.z < min.z)
  9299. min.z = v.z;
  9300. if (v.x > max.x)
  9301. max.x = v.x;
  9302. if (v.y > max.y)
  9303. max.y = v.y;
  9304. if (v.z > max.z)
  9305. max.z = v.z;
  9306. };
  9307. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9308. for (var prop in source) {
  9309. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9310. continue;
  9311. }
  9312. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9313. continue;
  9314. }
  9315. var sourceValue = source[prop];
  9316. var typeOfSourceValue = typeof sourceValue;
  9317. if (typeOfSourceValue === "function") {
  9318. continue;
  9319. }
  9320. try {
  9321. if (typeOfSourceValue === "object") {
  9322. if (sourceValue instanceof Array) {
  9323. destination[prop] = [];
  9324. if (sourceValue.length > 0) {
  9325. if (typeof sourceValue[0] == "object") {
  9326. for (var index = 0; index < sourceValue.length; index++) {
  9327. var clonedValue = cloneValue(sourceValue[index], destination);
  9328. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9329. destination[prop].push(clonedValue);
  9330. }
  9331. }
  9332. }
  9333. else {
  9334. destination[prop] = sourceValue.slice(0);
  9335. }
  9336. }
  9337. }
  9338. else {
  9339. destination[prop] = cloneValue(sourceValue, destination);
  9340. }
  9341. }
  9342. else {
  9343. destination[prop] = sourceValue;
  9344. }
  9345. }
  9346. catch (e) {
  9347. // Just ignore error (it could be because of a read-only property)
  9348. }
  9349. }
  9350. };
  9351. Tools.IsEmpty = function (obj) {
  9352. for (var i in obj) {
  9353. if (obj.hasOwnProperty(i)) {
  9354. return false;
  9355. }
  9356. }
  9357. return true;
  9358. };
  9359. Tools.RegisterTopRootEvents = function (events) {
  9360. for (var index = 0; index < events.length; index++) {
  9361. var event = events[index];
  9362. window.addEventListener(event.name, event.handler, false);
  9363. try {
  9364. if (window.parent) {
  9365. window.parent.addEventListener(event.name, event.handler, false);
  9366. }
  9367. }
  9368. catch (e) {
  9369. // Silently fails...
  9370. }
  9371. }
  9372. };
  9373. Tools.UnregisterTopRootEvents = function (events) {
  9374. for (var index = 0; index < events.length; index++) {
  9375. var event = events[index];
  9376. window.removeEventListener(event.name, event.handler);
  9377. try {
  9378. if (window.parent) {
  9379. window.parent.removeEventListener(event.name, event.handler);
  9380. }
  9381. }
  9382. catch (e) {
  9383. // Silently fails...
  9384. }
  9385. }
  9386. };
  9387. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9388. if (mimeType === void 0) { mimeType = "image/png"; }
  9389. // Read the contents of the framebuffer
  9390. var numberOfChannelsByLine = width * 4;
  9391. var halfHeight = height / 2;
  9392. //Reading datas from WebGL
  9393. var data = engine.readPixels(0, 0, width, height);
  9394. //To flip image on Y axis.
  9395. for (var i = 0; i < halfHeight; i++) {
  9396. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9397. var currentCell = j + i * numberOfChannelsByLine;
  9398. var targetLine = height - i - 1;
  9399. var targetCell = j + targetLine * numberOfChannelsByLine;
  9400. var temp = data[currentCell];
  9401. data[currentCell] = data[targetCell];
  9402. data[targetCell] = temp;
  9403. }
  9404. }
  9405. // Create a 2D canvas to store the result
  9406. if (!screenshotCanvas) {
  9407. screenshotCanvas = document.createElement('canvas');
  9408. }
  9409. screenshotCanvas.width = width;
  9410. screenshotCanvas.height = height;
  9411. var context = screenshotCanvas.getContext('2d');
  9412. if (context) {
  9413. // Copy the pixels to a 2D canvas
  9414. var imageData = context.createImageData(width, height);
  9415. var castData = (imageData.data);
  9416. castData.set(data);
  9417. context.putImageData(imageData, 0, 0);
  9418. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9419. }
  9420. };
  9421. /**
  9422. * Converts the canvas data to blob.
  9423. * This acts as a polyfill for browsers not supporting the to blob function.
  9424. * @param canvas Defines the canvas to extract the data from
  9425. * @param successCallback Defines the callback triggered once the data are available
  9426. * @param mimeType Defines the mime type of the result
  9427. */
  9428. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9429. if (mimeType === void 0) { mimeType = "image/png"; }
  9430. // We need HTMLCanvasElement.toBlob for HD screenshots
  9431. if (!canvas.toBlob) {
  9432. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9433. canvas.toBlob = function (callback, type, quality) {
  9434. var _this = this;
  9435. setTimeout(function () {
  9436. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9437. for (var i = 0; i < len; i++) {
  9438. arr[i] = binStr.charCodeAt(i);
  9439. }
  9440. callback(new Blob([arr]));
  9441. });
  9442. };
  9443. }
  9444. canvas.toBlob(function (blob) {
  9445. successCallback(blob);
  9446. }, mimeType);
  9447. };
  9448. /**
  9449. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9450. * @param successCallback Defines the callback triggered once the data are available
  9451. * @param mimeType Defines the mime type of the result
  9452. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9453. */
  9454. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9455. if (mimeType === void 0) { mimeType = "image/png"; }
  9456. if (successCallback) {
  9457. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9458. successCallback(base64Image);
  9459. }
  9460. else {
  9461. this.ToBlob(screenshotCanvas, function (blob) {
  9462. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9463. if (("download" in document.createElement("a"))) {
  9464. if (!fileName) {
  9465. var date = new Date();
  9466. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9467. fileName = "screenshot_" + stringDate + ".png";
  9468. }
  9469. Tools.Download(blob, fileName);
  9470. }
  9471. else {
  9472. var url = URL.createObjectURL(blob);
  9473. var newWindow = window.open("");
  9474. if (!newWindow)
  9475. return;
  9476. var img = newWindow.document.createElement("img");
  9477. img.onload = function () {
  9478. // no longer need to read the blob so it's revoked
  9479. URL.revokeObjectURL(url);
  9480. };
  9481. img.src = url;
  9482. newWindow.document.body.appendChild(img);
  9483. }
  9484. }, mimeType);
  9485. }
  9486. };
  9487. /**
  9488. * Downloads a blob in the browser
  9489. * @param blob defines the blob to download
  9490. * @param fileName defines the name of the downloaded file
  9491. */
  9492. Tools.Download = function (blob, fileName) {
  9493. if (navigator && navigator.msSaveBlob) {
  9494. navigator.msSaveBlob(blob, fileName);
  9495. return;
  9496. }
  9497. var url = window.URL.createObjectURL(blob);
  9498. var a = document.createElement("a");
  9499. document.body.appendChild(a);
  9500. a.style.display = "none";
  9501. a.href = url;
  9502. a.download = fileName;
  9503. a.addEventListener("click", function () {
  9504. if (a.parentElement) {
  9505. a.parentElement.removeChild(a);
  9506. }
  9507. });
  9508. a.click();
  9509. window.URL.revokeObjectURL(url);
  9510. };
  9511. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9512. if (mimeType === void 0) { mimeType = "image/png"; }
  9513. var width;
  9514. var height;
  9515. // If a precision value is specified
  9516. if (size.precision) {
  9517. width = Math.round(engine.getRenderWidth() * size.precision);
  9518. height = Math.round(width / engine.getAspectRatio(camera));
  9519. }
  9520. else if (size.width && size.height) {
  9521. width = size.width;
  9522. height = size.height;
  9523. }
  9524. //If passing only width, computing height to keep display canvas ratio.
  9525. else if (size.width && !size.height) {
  9526. width = size.width;
  9527. height = Math.round(width / engine.getAspectRatio(camera));
  9528. }
  9529. //If passing only height, computing width to keep display canvas ratio.
  9530. else if (size.height && !size.width) {
  9531. height = size.height;
  9532. width = Math.round(height * engine.getAspectRatio(camera));
  9533. }
  9534. //Assuming here that "size" parameter is a number
  9535. else if (!isNaN(size)) {
  9536. height = size;
  9537. width = size;
  9538. }
  9539. else {
  9540. Tools.Error("Invalid 'size' parameter !");
  9541. return;
  9542. }
  9543. if (!screenshotCanvas) {
  9544. screenshotCanvas = document.createElement('canvas');
  9545. }
  9546. screenshotCanvas.width = width;
  9547. screenshotCanvas.height = height;
  9548. var renderContext = screenshotCanvas.getContext("2d");
  9549. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9550. var newWidth = width;
  9551. var newHeight = newWidth / ratio;
  9552. if (newHeight > height) {
  9553. newHeight = height;
  9554. newWidth = newHeight * ratio;
  9555. }
  9556. var offsetX = Math.max(0, width - newWidth) / 2;
  9557. var offsetY = Math.max(0, height - newHeight) / 2;
  9558. var renderingCanvas = engine.getRenderingCanvas();
  9559. if (renderContext && renderingCanvas) {
  9560. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9561. }
  9562. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9563. };
  9564. /**
  9565. * Generates an image screenshot from the specified camera.
  9566. *
  9567. * @param engine The engine to use for rendering
  9568. * @param camera The camera to use for rendering
  9569. * @param size This parameter can be set to a single number or to an object with the
  9570. * following (optional) properties: precision, width, height. If a single number is passed,
  9571. * it will be used for both width and height. If an object is passed, the screenshot size
  9572. * will be derived from the parameters. The precision property is a multiplier allowing
  9573. * rendering at a higher or lower resolution.
  9574. * @param successCallback The callback receives a single parameter which contains the
  9575. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9576. * src parameter of an <img> to display it.
  9577. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9578. * Check your browser for supported MIME types.
  9579. * @param samples Texture samples (default: 1)
  9580. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9581. * @param fileName A name for for the downloaded file.
  9582. * @constructor
  9583. */
  9584. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9585. if (mimeType === void 0) { mimeType = "image/png"; }
  9586. if (samples === void 0) { samples = 1; }
  9587. if (antialiasing === void 0) { antialiasing = false; }
  9588. var width;
  9589. var height;
  9590. //If a precision value is specified
  9591. if (size.precision) {
  9592. width = Math.round(engine.getRenderWidth() * size.precision);
  9593. height = Math.round(width / engine.getAspectRatio(camera));
  9594. size = { width: width, height: height };
  9595. }
  9596. else if (size.width && size.height) {
  9597. width = size.width;
  9598. height = size.height;
  9599. }
  9600. //If passing only width, computing height to keep display canvas ratio.
  9601. else if (size.width && !size.height) {
  9602. width = size.width;
  9603. height = Math.round(width / engine.getAspectRatio(camera));
  9604. size = { width: width, height: height };
  9605. }
  9606. //If passing only height, computing width to keep display canvas ratio.
  9607. else if (size.height && !size.width) {
  9608. height = size.height;
  9609. width = Math.round(height * engine.getAspectRatio(camera));
  9610. size = { width: width, height: height };
  9611. }
  9612. //Assuming here that "size" parameter is a number
  9613. else if (!isNaN(size)) {
  9614. height = size;
  9615. width = size;
  9616. }
  9617. else {
  9618. Tools.Error("Invalid 'size' parameter !");
  9619. return;
  9620. }
  9621. var scene = camera.getScene();
  9622. var previousCamera = null;
  9623. if (scene.activeCamera !== camera) {
  9624. previousCamera = scene.activeCamera;
  9625. scene.activeCamera = camera;
  9626. }
  9627. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9628. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9629. texture.renderList = null;
  9630. texture.samples = samples;
  9631. if (antialiasing) {
  9632. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9633. }
  9634. texture.onAfterRenderObservable.add(function () {
  9635. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9636. });
  9637. scene.incrementRenderId();
  9638. scene.resetCachedMaterial();
  9639. texture.render(true);
  9640. texture.dispose();
  9641. if (previousCamera) {
  9642. scene.activeCamera = previousCamera;
  9643. }
  9644. camera.getProjectionMatrix(true); // Force cache refresh;
  9645. };
  9646. // XHR response validator for local file scenario
  9647. Tools.ValidateXHRData = function (xhr, dataType) {
  9648. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9649. if (dataType === void 0) { dataType = 7; }
  9650. try {
  9651. if (dataType & 1) {
  9652. if (xhr.responseText && xhr.responseText.length > 0) {
  9653. return true;
  9654. }
  9655. else if (dataType === 1) {
  9656. return false;
  9657. }
  9658. }
  9659. if (dataType & 2) {
  9660. // Check header width and height since there is no "TGA" magic number
  9661. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9662. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9663. return true;
  9664. }
  9665. else if (dataType === 2) {
  9666. return false;
  9667. }
  9668. }
  9669. if (dataType & 4) {
  9670. // Check for the "DDS" magic number
  9671. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9672. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9673. return true;
  9674. }
  9675. else {
  9676. return false;
  9677. }
  9678. }
  9679. }
  9680. catch (e) {
  9681. // Global protection
  9682. }
  9683. return false;
  9684. };
  9685. /**
  9686. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9687. * Be aware Math.random() could cause collisions, but:
  9688. * "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"
  9689. */
  9690. Tools.RandomId = function () {
  9691. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9692. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9693. return v.toString(16);
  9694. });
  9695. };
  9696. /**
  9697. * Test if the given uri is a base64 string.
  9698. * @param uri The uri to test
  9699. * @return True if the uri is a base64 string or false otherwise.
  9700. */
  9701. Tools.IsBase64 = function (uri) {
  9702. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9703. };
  9704. /**
  9705. * Decode the given base64 uri.
  9706. * @param uri The uri to decode
  9707. * @return The decoded base64 data.
  9708. */
  9709. Tools.DecodeBase64 = function (uri) {
  9710. var decodedString = atob(uri.split(",")[1]);
  9711. var bufferLength = decodedString.length;
  9712. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9713. for (var i = 0; i < bufferLength; i++) {
  9714. bufferView[i] = decodedString.charCodeAt(i);
  9715. }
  9716. return bufferView.buffer;
  9717. };
  9718. Object.defineProperty(Tools, "NoneLogLevel", {
  9719. get: function () {
  9720. return Tools._NoneLogLevel;
  9721. },
  9722. enumerable: true,
  9723. configurable: true
  9724. });
  9725. Object.defineProperty(Tools, "MessageLogLevel", {
  9726. get: function () {
  9727. return Tools._MessageLogLevel;
  9728. },
  9729. enumerable: true,
  9730. configurable: true
  9731. });
  9732. Object.defineProperty(Tools, "WarningLogLevel", {
  9733. get: function () {
  9734. return Tools._WarningLogLevel;
  9735. },
  9736. enumerable: true,
  9737. configurable: true
  9738. });
  9739. Object.defineProperty(Tools, "ErrorLogLevel", {
  9740. get: function () {
  9741. return Tools._ErrorLogLevel;
  9742. },
  9743. enumerable: true,
  9744. configurable: true
  9745. });
  9746. Object.defineProperty(Tools, "AllLogLevel", {
  9747. get: function () {
  9748. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9749. },
  9750. enumerable: true,
  9751. configurable: true
  9752. });
  9753. Tools._AddLogEntry = function (entry) {
  9754. Tools._LogCache = entry + Tools._LogCache;
  9755. if (Tools.OnNewCacheEntry) {
  9756. Tools.OnNewCacheEntry(entry);
  9757. }
  9758. };
  9759. Tools._FormatMessage = function (message) {
  9760. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9761. var date = new Date();
  9762. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9763. };
  9764. Tools._LogDisabled = function (message) {
  9765. // nothing to do
  9766. };
  9767. Tools._LogEnabled = function (message) {
  9768. var formattedMessage = Tools._FormatMessage(message);
  9769. console.log("BJS - " + formattedMessage);
  9770. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9771. Tools._AddLogEntry(entry);
  9772. };
  9773. Tools._WarnDisabled = function (message) {
  9774. // nothing to do
  9775. };
  9776. Tools._WarnEnabled = function (message) {
  9777. var formattedMessage = Tools._FormatMessage(message);
  9778. console.warn("BJS - " + formattedMessage);
  9779. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9780. Tools._AddLogEntry(entry);
  9781. };
  9782. Tools._ErrorDisabled = function (message) {
  9783. // nothing to do
  9784. };
  9785. Tools._ErrorEnabled = function (message) {
  9786. Tools.errorsCount++;
  9787. var formattedMessage = Tools._FormatMessage(message);
  9788. console.error("BJS - " + formattedMessage);
  9789. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9790. Tools._AddLogEntry(entry);
  9791. };
  9792. Object.defineProperty(Tools, "LogCache", {
  9793. get: function () {
  9794. return Tools._LogCache;
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Tools.ClearLogCache = function () {
  9800. Tools._LogCache = "";
  9801. Tools.errorsCount = 0;
  9802. };
  9803. Object.defineProperty(Tools, "LogLevels", {
  9804. set: function (level) {
  9805. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9806. Tools.Log = Tools._LogEnabled;
  9807. }
  9808. else {
  9809. Tools.Log = Tools._LogDisabled;
  9810. }
  9811. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9812. Tools.Warn = Tools._WarnEnabled;
  9813. }
  9814. else {
  9815. Tools.Warn = Tools._WarnDisabled;
  9816. }
  9817. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9818. Tools.Error = Tools._ErrorEnabled;
  9819. }
  9820. else {
  9821. Tools.Error = Tools._ErrorDisabled;
  9822. }
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Tools.IsWindowObjectExist = function () {
  9828. return (typeof window) !== "undefined";
  9829. };
  9830. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9831. get: function () {
  9832. return Tools._PerformanceNoneLogLevel;
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9838. get: function () {
  9839. return Tools._PerformanceUserMarkLogLevel;
  9840. },
  9841. enumerable: true,
  9842. configurable: true
  9843. });
  9844. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9845. get: function () {
  9846. return Tools._PerformanceConsoleLogLevel;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9852. set: function (level) {
  9853. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9854. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9855. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9856. return;
  9857. }
  9858. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9859. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9860. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9861. return;
  9862. }
  9863. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9864. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9870. };
  9871. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9872. };
  9873. Tools._StartUserMark = function (counterName, condition) {
  9874. if (condition === void 0) { condition = true; }
  9875. if (!Tools._performance) {
  9876. if (!Tools.IsWindowObjectExist()) {
  9877. return;
  9878. }
  9879. Tools._performance = window.performance;
  9880. }
  9881. if (!condition || !Tools._performance.mark) {
  9882. return;
  9883. }
  9884. Tools._performance.mark(counterName + "-Begin");
  9885. };
  9886. Tools._EndUserMark = function (counterName, condition) {
  9887. if (condition === void 0) { condition = true; }
  9888. if (!condition || !Tools._performance.mark) {
  9889. return;
  9890. }
  9891. Tools._performance.mark(counterName + "-End");
  9892. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9893. };
  9894. Tools._StartPerformanceConsole = function (counterName, condition) {
  9895. if (condition === void 0) { condition = true; }
  9896. if (!condition) {
  9897. return;
  9898. }
  9899. Tools._StartUserMark(counterName, condition);
  9900. if (console.time) {
  9901. console.time(counterName);
  9902. }
  9903. };
  9904. Tools._EndPerformanceConsole = function (counterName, condition) {
  9905. if (condition === void 0) { condition = true; }
  9906. if (!condition) {
  9907. return;
  9908. }
  9909. Tools._EndUserMark(counterName, condition);
  9910. if (console.time) {
  9911. console.timeEnd(counterName);
  9912. }
  9913. };
  9914. Object.defineProperty(Tools, "Now", {
  9915. get: function () {
  9916. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9917. return window.performance.now();
  9918. }
  9919. return Date.now();
  9920. },
  9921. enumerable: true,
  9922. configurable: true
  9923. });
  9924. /**
  9925. * This method will return the name of the class used to create the instance of the given object.
  9926. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9927. * @param object the object to get the class name from
  9928. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9929. */
  9930. Tools.GetClassName = function (object, isType) {
  9931. if (isType === void 0) { isType = false; }
  9932. var name = null;
  9933. if (!isType && object.getClassName) {
  9934. name = object.getClassName();
  9935. }
  9936. else {
  9937. if (object instanceof Object) {
  9938. var classObj = isType ? object : Object.getPrototypeOf(object);
  9939. name = classObj.constructor["__bjsclassName__"];
  9940. }
  9941. if (!name) {
  9942. name = typeof object;
  9943. }
  9944. }
  9945. return name;
  9946. };
  9947. Tools.First = function (array, predicate) {
  9948. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9949. var el = array_1[_i];
  9950. if (predicate(el)) {
  9951. return el;
  9952. }
  9953. }
  9954. return null;
  9955. };
  9956. /**
  9957. * This method will return the name of the full name of the class, including its owning module (if any).
  9958. * 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).
  9959. * @param object the object to get the class name from
  9960. * @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.
  9961. */
  9962. Tools.getFullClassName = function (object, isType) {
  9963. if (isType === void 0) { isType = false; }
  9964. var className = null;
  9965. var moduleName = null;
  9966. if (!isType && object.getClassName) {
  9967. className = object.getClassName();
  9968. }
  9969. else {
  9970. if (object instanceof Object) {
  9971. var classObj = isType ? object : Object.getPrototypeOf(object);
  9972. className = classObj.constructor["__bjsclassName__"];
  9973. moduleName = classObj.constructor["__bjsmoduleName__"];
  9974. }
  9975. if (!className) {
  9976. className = typeof object;
  9977. }
  9978. }
  9979. if (!className) {
  9980. return null;
  9981. }
  9982. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9983. };
  9984. /**
  9985. * 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.
  9986. * @param array
  9987. */
  9988. Tools.arrayOrStringFeeder = function (array) {
  9989. return function (index) {
  9990. if (index >= array.length) {
  9991. return null;
  9992. }
  9993. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9994. if (val && val.getHashCode) {
  9995. val = val.getHashCode();
  9996. }
  9997. if (typeof val === "string") {
  9998. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9999. }
  10000. return val;
  10001. };
  10002. };
  10003. /**
  10004. * Compute the hashCode of a stream of number
  10005. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10006. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10007. * @return the hash code computed
  10008. */
  10009. Tools.hashCodeFromStream = function (feeder) {
  10010. // Based from here: http://stackoverflow.com/a/7616484/802124
  10011. var hash = 0;
  10012. var index = 0;
  10013. var chr = feeder(index++);
  10014. while (chr != null) {
  10015. hash = ((hash << 5) - hash) + chr;
  10016. hash |= 0; // Convert to 32bit integer
  10017. chr = feeder(index++);
  10018. }
  10019. return hash;
  10020. };
  10021. /**
  10022. * Returns a promise that resolves after the given amount of time.
  10023. * @param delay Number of milliseconds to delay
  10024. * @returns Promise that resolves after the given amount of time
  10025. */
  10026. Tools.DelayAsync = function (delay) {
  10027. return new Promise(function (resolve) {
  10028. setTimeout(function () {
  10029. resolve();
  10030. }, delay);
  10031. });
  10032. };
  10033. /**
  10034. * Gets the current gradient from an array of IValueGradient
  10035. * @param ratio defines the current ratio to get
  10036. * @param gradients defines the array of IValueGradient
  10037. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10038. */
  10039. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10040. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10041. var currentGradient = gradients[gradientIndex];
  10042. var nextGradient = gradients[gradientIndex + 1];
  10043. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10044. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10045. updateFunc(currentGradient, nextGradient, scale);
  10046. }
  10047. }
  10048. };
  10049. Tools.BaseUrl = "";
  10050. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10051. /**
  10052. * Default behaviour for cors in the application.
  10053. * It can be a string if the expected behavior is identical in the entire app.
  10054. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10055. */
  10056. Tools.CorsBehavior = "anonymous";
  10057. Tools.UseFallbackTexture = true;
  10058. /**
  10059. * Use this object to register external classes like custom textures or material
  10060. * to allow the laoders to instantiate them
  10061. */
  10062. Tools.RegisteredExternalClasses = {};
  10063. // Used in case of a texture loading problem
  10064. 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";
  10065. Tools._tmpFloatArray = new Float32Array(1);
  10066. Tools.PreprocessUrl = function (url) {
  10067. return url;
  10068. };
  10069. // Logs
  10070. Tools._NoneLogLevel = 0;
  10071. Tools._MessageLogLevel = 1;
  10072. Tools._WarningLogLevel = 2;
  10073. Tools._ErrorLogLevel = 4;
  10074. Tools._LogCache = "";
  10075. Tools.errorsCount = 0;
  10076. Tools.Log = Tools._LogEnabled;
  10077. Tools.Warn = Tools._WarnEnabled;
  10078. Tools.Error = Tools._ErrorEnabled;
  10079. // Performances
  10080. Tools._PerformanceNoneLogLevel = 0;
  10081. Tools._PerformanceUserMarkLogLevel = 1;
  10082. Tools._PerformanceConsoleLogLevel = 2;
  10083. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10084. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10085. return Tools;
  10086. }());
  10087. BABYLON.Tools = Tools;
  10088. /**
  10089. * This class is used to track a performance counter which is number based.
  10090. * The user has access to many properties which give statistics of different nature
  10091. *
  10092. * The implementer can track two kinds of Performance Counter: time and count
  10093. * 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.
  10094. * 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.
  10095. */
  10096. var PerfCounter = /** @class */ (function () {
  10097. function PerfCounter() {
  10098. this._startMonitoringTime = 0;
  10099. this._min = 0;
  10100. this._max = 0;
  10101. this._average = 0;
  10102. this._lastSecAverage = 0;
  10103. this._current = 0;
  10104. this._totalValueCount = 0;
  10105. this._totalAccumulated = 0;
  10106. this._lastSecAccumulated = 0;
  10107. this._lastSecTime = 0;
  10108. this._lastSecValueCount = 0;
  10109. }
  10110. Object.defineProperty(PerfCounter.prototype, "min", {
  10111. /**
  10112. * Returns the smallest value ever
  10113. */
  10114. get: function () {
  10115. return this._min;
  10116. },
  10117. enumerable: true,
  10118. configurable: true
  10119. });
  10120. Object.defineProperty(PerfCounter.prototype, "max", {
  10121. /**
  10122. * Returns the biggest value ever
  10123. */
  10124. get: function () {
  10125. return this._max;
  10126. },
  10127. enumerable: true,
  10128. configurable: true
  10129. });
  10130. Object.defineProperty(PerfCounter.prototype, "average", {
  10131. /**
  10132. * Returns the average value since the performance counter is running
  10133. */
  10134. get: function () {
  10135. return this._average;
  10136. },
  10137. enumerable: true,
  10138. configurable: true
  10139. });
  10140. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10141. /**
  10142. * Returns the average value of the last second the counter was monitored
  10143. */
  10144. get: function () {
  10145. return this._lastSecAverage;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(PerfCounter.prototype, "current", {
  10151. /**
  10152. * Returns the current value
  10153. */
  10154. get: function () {
  10155. return this._current;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(PerfCounter.prototype, "total", {
  10161. get: function () {
  10162. return this._totalAccumulated;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(PerfCounter.prototype, "count", {
  10168. get: function () {
  10169. return this._totalValueCount;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. /**
  10175. * Call this method to start monitoring a new frame.
  10176. * 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.
  10177. */
  10178. PerfCounter.prototype.fetchNewFrame = function () {
  10179. this._totalValueCount++;
  10180. this._current = 0;
  10181. this._lastSecValueCount++;
  10182. };
  10183. /**
  10184. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10185. * @param newCount the count value to add to the monitored count
  10186. * @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.
  10187. */
  10188. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10189. if (!PerfCounter.Enabled) {
  10190. return;
  10191. }
  10192. this._current += newCount;
  10193. if (fetchResult) {
  10194. this._fetchResult();
  10195. }
  10196. };
  10197. /**
  10198. * Start monitoring this performance counter
  10199. */
  10200. PerfCounter.prototype.beginMonitoring = function () {
  10201. if (!PerfCounter.Enabled) {
  10202. return;
  10203. }
  10204. this._startMonitoringTime = Tools.Now;
  10205. };
  10206. /**
  10207. * Compute the time lapsed since the previous beginMonitoring() call.
  10208. * @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
  10209. */
  10210. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10211. if (newFrame === void 0) { newFrame = true; }
  10212. if (!PerfCounter.Enabled) {
  10213. return;
  10214. }
  10215. if (newFrame) {
  10216. this.fetchNewFrame();
  10217. }
  10218. var currentTime = Tools.Now;
  10219. this._current = currentTime - this._startMonitoringTime;
  10220. if (newFrame) {
  10221. this._fetchResult();
  10222. }
  10223. };
  10224. PerfCounter.prototype._fetchResult = function () {
  10225. this._totalAccumulated += this._current;
  10226. this._lastSecAccumulated += this._current;
  10227. // Min/Max update
  10228. this._min = Math.min(this._min, this._current);
  10229. this._max = Math.max(this._max, this._current);
  10230. this._average = this._totalAccumulated / this._totalValueCount;
  10231. // Reset last sec?
  10232. var now = Tools.Now;
  10233. if ((now - this._lastSecTime) > 1000) {
  10234. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10235. this._lastSecTime = now;
  10236. this._lastSecAccumulated = 0;
  10237. this._lastSecValueCount = 0;
  10238. }
  10239. };
  10240. PerfCounter.Enabled = true;
  10241. return PerfCounter;
  10242. }());
  10243. BABYLON.PerfCounter = PerfCounter;
  10244. /**
  10245. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10246. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10247. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10248. * @param name The name of the class, case should be preserved
  10249. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10250. */
  10251. function className(name, module) {
  10252. return function (target) {
  10253. target["__bjsclassName__"] = name;
  10254. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10255. };
  10256. }
  10257. BABYLON.className = className;
  10258. /**
  10259. * An implementation of a loop for asynchronous functions.
  10260. */
  10261. var AsyncLoop = /** @class */ (function () {
  10262. /**
  10263. * Constroctor.
  10264. * @param iterations the number of iterations.
  10265. * @param _fn the function to run each iteration
  10266. * @param _successCallback the callback that will be called upon succesful execution
  10267. * @param offset starting offset.
  10268. */
  10269. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10270. if (offset === void 0) { offset = 0; }
  10271. this.iterations = iterations;
  10272. this._fn = _fn;
  10273. this._successCallback = _successCallback;
  10274. this.index = offset - 1;
  10275. this._done = false;
  10276. }
  10277. /**
  10278. * Execute the next iteration. Must be called after the last iteration was finished.
  10279. */
  10280. AsyncLoop.prototype.executeNext = function () {
  10281. if (!this._done) {
  10282. if (this.index + 1 < this.iterations) {
  10283. ++this.index;
  10284. this._fn(this);
  10285. }
  10286. else {
  10287. this.breakLoop();
  10288. }
  10289. }
  10290. };
  10291. /**
  10292. * Break the loop and run the success callback.
  10293. */
  10294. AsyncLoop.prototype.breakLoop = function () {
  10295. this._done = true;
  10296. this._successCallback();
  10297. };
  10298. /**
  10299. * Helper function
  10300. */
  10301. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10302. if (offset === void 0) { offset = 0; }
  10303. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10304. loop.executeNext();
  10305. return loop;
  10306. };
  10307. /**
  10308. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10309. * @param iterations total number of iterations
  10310. * @param syncedIterations number of synchronous iterations in each async iteration.
  10311. * @param fn the function to call each iteration.
  10312. * @param callback a success call back that will be called when iterating stops.
  10313. * @param breakFunction a break condition (optional)
  10314. * @param timeout timeout settings for the setTimeout function. default - 0.
  10315. * @constructor
  10316. */
  10317. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10318. if (timeout === void 0) { timeout = 0; }
  10319. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10320. if (breakFunction && breakFunction())
  10321. loop.breakLoop();
  10322. else {
  10323. setTimeout(function () {
  10324. for (var i = 0; i < syncedIterations; ++i) {
  10325. var iteration = (loop.index * syncedIterations) + i;
  10326. if (iteration >= iterations)
  10327. break;
  10328. fn(iteration);
  10329. if (breakFunction && breakFunction()) {
  10330. loop.breakLoop();
  10331. break;
  10332. }
  10333. }
  10334. loop.executeNext();
  10335. }, timeout);
  10336. }
  10337. }, callback);
  10338. };
  10339. return AsyncLoop;
  10340. }());
  10341. BABYLON.AsyncLoop = AsyncLoop;
  10342. })(BABYLON || (BABYLON = {}));
  10343. //# sourceMappingURL=babylon.tools.js.map
  10344. var BABYLON;
  10345. (function (BABYLON) {
  10346. var PromiseStates;
  10347. (function (PromiseStates) {
  10348. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10349. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10350. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10351. })(PromiseStates || (PromiseStates = {}));
  10352. var FulFillmentAgregator = /** @class */ (function () {
  10353. function FulFillmentAgregator() {
  10354. this.count = 0;
  10355. this.target = 0;
  10356. this.results = [];
  10357. }
  10358. return FulFillmentAgregator;
  10359. }());
  10360. var InternalPromise = /** @class */ (function () {
  10361. function InternalPromise(resolver) {
  10362. var _this = this;
  10363. this._state = PromiseStates.Pending;
  10364. this._children = new Array();
  10365. this._rejectWasConsumed = false;
  10366. if (!resolver) {
  10367. return;
  10368. }
  10369. try {
  10370. resolver(function (value) {
  10371. _this._resolve(value);
  10372. }, function (reason) {
  10373. _this._reject(reason);
  10374. });
  10375. }
  10376. catch (e) {
  10377. this._reject(e);
  10378. }
  10379. }
  10380. Object.defineProperty(InternalPromise.prototype, "_result", {
  10381. get: function () {
  10382. return this._resultValue;
  10383. },
  10384. set: function (value) {
  10385. this._resultValue = value;
  10386. if (this._parent && this._parent._result === undefined) {
  10387. this._parent._result = value;
  10388. }
  10389. },
  10390. enumerable: true,
  10391. configurable: true
  10392. });
  10393. InternalPromise.prototype.catch = function (onRejected) {
  10394. return this.then(undefined, onRejected);
  10395. };
  10396. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10397. var _this = this;
  10398. var newPromise = new InternalPromise();
  10399. newPromise._onFulfilled = onFulfilled;
  10400. newPromise._onRejected = onRejected;
  10401. // Composition
  10402. this._children.push(newPromise);
  10403. newPromise._parent = this;
  10404. if (this._state !== PromiseStates.Pending) {
  10405. BABYLON.Tools.SetImmediate(function () {
  10406. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10407. var returnedValue = newPromise._resolve(_this._result);
  10408. if (returnedValue !== undefined && returnedValue !== null) {
  10409. if (returnedValue._state !== undefined) {
  10410. var returnedPromise = returnedValue;
  10411. newPromise._children.push(returnedPromise);
  10412. returnedPromise._parent = newPromise;
  10413. newPromise = returnedPromise;
  10414. }
  10415. else {
  10416. newPromise._result = returnedValue;
  10417. }
  10418. }
  10419. }
  10420. else {
  10421. newPromise._reject(_this._reason);
  10422. }
  10423. });
  10424. }
  10425. return newPromise;
  10426. };
  10427. InternalPromise.prototype._moveChildren = function (children) {
  10428. var _this = this;
  10429. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10430. this._children.forEach(function (child) {
  10431. child._parent = _this;
  10432. });
  10433. if (this._state === PromiseStates.Fulfilled) {
  10434. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10435. var child = _b[_i];
  10436. child._resolve(this._result);
  10437. }
  10438. }
  10439. else if (this._state === PromiseStates.Rejected) {
  10440. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10441. var child = _d[_c];
  10442. child._reject(this._reason);
  10443. }
  10444. }
  10445. var _a;
  10446. };
  10447. InternalPromise.prototype._resolve = function (value) {
  10448. try {
  10449. this._state = PromiseStates.Fulfilled;
  10450. var returnedValue = null;
  10451. if (this._onFulfilled) {
  10452. returnedValue = this._onFulfilled(value);
  10453. }
  10454. if (returnedValue !== undefined && returnedValue !== null) {
  10455. if (returnedValue._state !== undefined) {
  10456. // Transmit children
  10457. var returnedPromise = returnedValue;
  10458. returnedPromise._parent = this;
  10459. returnedPromise._moveChildren(this._children);
  10460. value = returnedPromise._result;
  10461. }
  10462. else {
  10463. value = returnedValue;
  10464. }
  10465. }
  10466. this._result = value;
  10467. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10468. var child = _a[_i];
  10469. child._resolve(value);
  10470. }
  10471. this._children.length = 0;
  10472. delete this._onFulfilled;
  10473. delete this._onRejected;
  10474. }
  10475. catch (e) {
  10476. this._reject(e, true);
  10477. }
  10478. };
  10479. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10480. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10481. this._state = PromiseStates.Rejected;
  10482. this._reason = reason;
  10483. if (this._onRejected && !onLocalThrow) {
  10484. try {
  10485. this._onRejected(reason);
  10486. this._rejectWasConsumed = true;
  10487. }
  10488. catch (e) {
  10489. reason = e;
  10490. }
  10491. }
  10492. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10493. var child = _a[_i];
  10494. if (this._rejectWasConsumed) {
  10495. child._resolve(null);
  10496. }
  10497. else {
  10498. child._reject(reason);
  10499. }
  10500. }
  10501. this._children.length = 0;
  10502. delete this._onFulfilled;
  10503. delete this._onRejected;
  10504. };
  10505. InternalPromise.resolve = function (value) {
  10506. var newPromise = new InternalPromise();
  10507. newPromise._resolve(value);
  10508. return newPromise;
  10509. };
  10510. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10511. promise.then(function (value) {
  10512. agregator.results[index] = value;
  10513. agregator.count++;
  10514. if (agregator.count === agregator.target) {
  10515. agregator.rootPromise._resolve(agregator.results);
  10516. }
  10517. return null;
  10518. }, function (reason) {
  10519. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10520. agregator.rootPromise._reject(reason);
  10521. }
  10522. });
  10523. };
  10524. InternalPromise.all = function (promises) {
  10525. var newPromise = new InternalPromise();
  10526. var agregator = new FulFillmentAgregator();
  10527. agregator.target = promises.length;
  10528. agregator.rootPromise = newPromise;
  10529. if (promises.length) {
  10530. for (var index = 0; index < promises.length; index++) {
  10531. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10532. }
  10533. }
  10534. else {
  10535. newPromise._resolve([]);
  10536. }
  10537. return newPromise;
  10538. };
  10539. InternalPromise.race = function (promises) {
  10540. var newPromise = new InternalPromise();
  10541. if (promises.length) {
  10542. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10543. var promise = promises_1[_i];
  10544. promise.then(function (value) {
  10545. if (newPromise) {
  10546. newPromise._resolve(value);
  10547. newPromise = null;
  10548. }
  10549. return null;
  10550. }, function (reason) {
  10551. if (newPromise) {
  10552. newPromise._reject(reason);
  10553. newPromise = null;
  10554. }
  10555. });
  10556. }
  10557. }
  10558. return newPromise;
  10559. };
  10560. return InternalPromise;
  10561. }());
  10562. /**
  10563. * Helper class that provides a small promise polyfill
  10564. */
  10565. var PromisePolyfill = /** @class */ (function () {
  10566. function PromisePolyfill() {
  10567. }
  10568. /**
  10569. * Static function used to check if the polyfill is required
  10570. * If this is the case then the function will inject the polyfill to window.Promise
  10571. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10572. */
  10573. PromisePolyfill.Apply = function (force) {
  10574. if (force === void 0) { force = false; }
  10575. if (force || typeof Promise === 'undefined') {
  10576. var root = window;
  10577. root.Promise = InternalPromise;
  10578. }
  10579. };
  10580. return PromisePolyfill;
  10581. }());
  10582. BABYLON.PromisePolyfill = PromisePolyfill;
  10583. })(BABYLON || (BABYLON = {}));
  10584. //# sourceMappingURL=babylon.promise.js.map
  10585. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10586. var BABYLON;
  10587. (function (BABYLON) {
  10588. /**
  10589. * Helper class to push actions to a pool of workers.
  10590. */
  10591. var WorkerPool = /** @class */ (function () {
  10592. /**
  10593. * Constructor
  10594. * @param workers Array of workers to use for actions
  10595. */
  10596. function WorkerPool(workers) {
  10597. this._pendingActions = new Array();
  10598. this._workerInfos = workers.map(function (worker) { return ({
  10599. worker: worker,
  10600. active: false
  10601. }); });
  10602. }
  10603. /**
  10604. * Terminates all workers and clears any pending actions.
  10605. */
  10606. WorkerPool.prototype.dispose = function () {
  10607. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10608. var workerInfo = _a[_i];
  10609. workerInfo.worker.terminate();
  10610. }
  10611. delete this._workerInfos;
  10612. delete this._pendingActions;
  10613. };
  10614. /**
  10615. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10616. * pended until a worker has completed its action.
  10617. * @param action The action to perform. Call onComplete when the action is complete.
  10618. */
  10619. WorkerPool.prototype.push = function (action) {
  10620. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10621. var workerInfo = _a[_i];
  10622. if (!workerInfo.active) {
  10623. this._execute(workerInfo, action);
  10624. return;
  10625. }
  10626. }
  10627. this._pendingActions.push(action);
  10628. };
  10629. WorkerPool.prototype._execute = function (workerInfo, action) {
  10630. var _this = this;
  10631. workerInfo.active = true;
  10632. action(workerInfo.worker, function () {
  10633. workerInfo.active = false;
  10634. var nextAction = _this._pendingActions.shift();
  10635. if (nextAction) {
  10636. _this._execute(workerInfo, nextAction);
  10637. }
  10638. });
  10639. };
  10640. return WorkerPool;
  10641. }());
  10642. BABYLON.WorkerPool = WorkerPool;
  10643. })(BABYLON || (BABYLON = {}));
  10644. //# sourceMappingURL=babylon.workerPool.js.map
  10645. var BABYLON;
  10646. (function (BABYLON) {
  10647. /**
  10648. * @hidden
  10649. **/
  10650. var _AlphaState = /** @class */ (function () {
  10651. /**
  10652. * Initializes the state.
  10653. */
  10654. function _AlphaState() {
  10655. this._isAlphaBlendDirty = false;
  10656. this._isBlendFunctionParametersDirty = false;
  10657. this._isBlendEquationParametersDirty = false;
  10658. this._isBlendConstantsDirty = false;
  10659. this._alphaBlend = false;
  10660. this._blendFunctionParameters = new Array(4);
  10661. this._blendEquationParameters = new Array(2);
  10662. this._blendConstants = new Array(4);
  10663. this.reset();
  10664. }
  10665. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10666. get: function () {
  10667. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10668. },
  10669. enumerable: true,
  10670. configurable: true
  10671. });
  10672. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10673. get: function () {
  10674. return this._alphaBlend;
  10675. },
  10676. set: function (value) {
  10677. if (this._alphaBlend === value) {
  10678. return;
  10679. }
  10680. this._alphaBlend = value;
  10681. this._isAlphaBlendDirty = true;
  10682. },
  10683. enumerable: true,
  10684. configurable: true
  10685. });
  10686. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10687. if (this._blendConstants[0] === r &&
  10688. this._blendConstants[1] === g &&
  10689. this._blendConstants[2] === b &&
  10690. this._blendConstants[3] === a) {
  10691. return;
  10692. }
  10693. this._blendConstants[0] = r;
  10694. this._blendConstants[1] = g;
  10695. this._blendConstants[2] = b;
  10696. this._blendConstants[3] = a;
  10697. this._isBlendConstantsDirty = true;
  10698. };
  10699. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10700. if (this._blendFunctionParameters[0] === value0 &&
  10701. this._blendFunctionParameters[1] === value1 &&
  10702. this._blendFunctionParameters[2] === value2 &&
  10703. this._blendFunctionParameters[3] === value3) {
  10704. return;
  10705. }
  10706. this._blendFunctionParameters[0] = value0;
  10707. this._blendFunctionParameters[1] = value1;
  10708. this._blendFunctionParameters[2] = value2;
  10709. this._blendFunctionParameters[3] = value3;
  10710. this._isBlendFunctionParametersDirty = true;
  10711. };
  10712. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10713. if (this._blendEquationParameters[0] === rgb &&
  10714. this._blendEquationParameters[1] === alpha) {
  10715. return;
  10716. }
  10717. this._blendEquationParameters[0] = rgb;
  10718. this._blendEquationParameters[1] = alpha;
  10719. this._isBlendEquationParametersDirty = true;
  10720. };
  10721. _AlphaState.prototype.reset = function () {
  10722. this._alphaBlend = false;
  10723. this._blendFunctionParameters[0] = null;
  10724. this._blendFunctionParameters[1] = null;
  10725. this._blendFunctionParameters[2] = null;
  10726. this._blendFunctionParameters[3] = null;
  10727. this._blendEquationParameters[0] = null;
  10728. this._blendEquationParameters[1] = null;
  10729. this._blendConstants[0] = null;
  10730. this._blendConstants[1] = null;
  10731. this._blendConstants[2] = null;
  10732. this._blendConstants[3] = null;
  10733. this._isAlphaBlendDirty = true;
  10734. this._isBlendFunctionParametersDirty = false;
  10735. this._isBlendEquationParametersDirty = false;
  10736. this._isBlendConstantsDirty = false;
  10737. };
  10738. _AlphaState.prototype.apply = function (gl) {
  10739. if (!this.isDirty) {
  10740. return;
  10741. }
  10742. // Alpha blend
  10743. if (this._isAlphaBlendDirty) {
  10744. if (this._alphaBlend) {
  10745. gl.enable(gl.BLEND);
  10746. }
  10747. else {
  10748. gl.disable(gl.BLEND);
  10749. }
  10750. this._isAlphaBlendDirty = false;
  10751. }
  10752. // Alpha function
  10753. if (this._isBlendFunctionParametersDirty) {
  10754. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10755. this._isBlendFunctionParametersDirty = false;
  10756. }
  10757. // Alpha equation
  10758. if (this._isBlendEquationParametersDirty) {
  10759. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10760. this._isBlendEquationParametersDirty = false;
  10761. }
  10762. // Constants
  10763. if (this._isBlendConstantsDirty) {
  10764. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10765. this._isBlendConstantsDirty = false;
  10766. }
  10767. };
  10768. return _AlphaState;
  10769. }());
  10770. BABYLON._AlphaState = _AlphaState;
  10771. })(BABYLON || (BABYLON = {}));
  10772. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10773. var BABYLON;
  10774. (function (BABYLON) {
  10775. /**
  10776. * @hidden
  10777. **/
  10778. var _DepthCullingState = /** @class */ (function () {
  10779. /**
  10780. * Initializes the state.
  10781. */
  10782. function _DepthCullingState() {
  10783. this._isDepthTestDirty = false;
  10784. this._isDepthMaskDirty = false;
  10785. this._isDepthFuncDirty = false;
  10786. this._isCullFaceDirty = false;
  10787. this._isCullDirty = false;
  10788. this._isZOffsetDirty = false;
  10789. this._isFrontFaceDirty = false;
  10790. this.reset();
  10791. }
  10792. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10793. get: function () {
  10794. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10800. get: function () {
  10801. return this._zOffset;
  10802. },
  10803. set: function (value) {
  10804. if (this._zOffset === value) {
  10805. return;
  10806. }
  10807. this._zOffset = value;
  10808. this._isZOffsetDirty = true;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10814. get: function () {
  10815. return this._cullFace;
  10816. },
  10817. set: function (value) {
  10818. if (this._cullFace === value) {
  10819. return;
  10820. }
  10821. this._cullFace = value;
  10822. this._isCullFaceDirty = true;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10828. get: function () {
  10829. return this._cull;
  10830. },
  10831. set: function (value) {
  10832. if (this._cull === value) {
  10833. return;
  10834. }
  10835. this._cull = value;
  10836. this._isCullDirty = true;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10842. get: function () {
  10843. return this._depthFunc;
  10844. },
  10845. set: function (value) {
  10846. if (this._depthFunc === value) {
  10847. return;
  10848. }
  10849. this._depthFunc = value;
  10850. this._isDepthFuncDirty = true;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10856. get: function () {
  10857. return this._depthMask;
  10858. },
  10859. set: function (value) {
  10860. if (this._depthMask === value) {
  10861. return;
  10862. }
  10863. this._depthMask = value;
  10864. this._isDepthMaskDirty = true;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10870. get: function () {
  10871. return this._depthTest;
  10872. },
  10873. set: function (value) {
  10874. if (this._depthTest === value) {
  10875. return;
  10876. }
  10877. this._depthTest = value;
  10878. this._isDepthTestDirty = true;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10884. get: function () {
  10885. return this._frontFace;
  10886. },
  10887. set: function (value) {
  10888. if (this._frontFace === value) {
  10889. return;
  10890. }
  10891. this._frontFace = value;
  10892. this._isFrontFaceDirty = true;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. _DepthCullingState.prototype.reset = function () {
  10898. this._depthMask = true;
  10899. this._depthTest = true;
  10900. this._depthFunc = null;
  10901. this._cullFace = null;
  10902. this._cull = null;
  10903. this._zOffset = 0;
  10904. this._frontFace = null;
  10905. this._isDepthTestDirty = true;
  10906. this._isDepthMaskDirty = true;
  10907. this._isDepthFuncDirty = false;
  10908. this._isCullFaceDirty = false;
  10909. this._isCullDirty = false;
  10910. this._isZOffsetDirty = false;
  10911. this._isFrontFaceDirty = false;
  10912. };
  10913. _DepthCullingState.prototype.apply = function (gl) {
  10914. if (!this.isDirty) {
  10915. return;
  10916. }
  10917. // Cull
  10918. if (this._isCullDirty) {
  10919. if (this.cull) {
  10920. gl.enable(gl.CULL_FACE);
  10921. }
  10922. else {
  10923. gl.disable(gl.CULL_FACE);
  10924. }
  10925. this._isCullDirty = false;
  10926. }
  10927. // Cull face
  10928. if (this._isCullFaceDirty) {
  10929. gl.cullFace(this.cullFace);
  10930. this._isCullFaceDirty = false;
  10931. }
  10932. // Depth mask
  10933. if (this._isDepthMaskDirty) {
  10934. gl.depthMask(this.depthMask);
  10935. this._isDepthMaskDirty = false;
  10936. }
  10937. // Depth test
  10938. if (this._isDepthTestDirty) {
  10939. if (this.depthTest) {
  10940. gl.enable(gl.DEPTH_TEST);
  10941. }
  10942. else {
  10943. gl.disable(gl.DEPTH_TEST);
  10944. }
  10945. this._isDepthTestDirty = false;
  10946. }
  10947. // Depth func
  10948. if (this._isDepthFuncDirty) {
  10949. gl.depthFunc(this.depthFunc);
  10950. this._isDepthFuncDirty = false;
  10951. }
  10952. // zOffset
  10953. if (this._isZOffsetDirty) {
  10954. if (this.zOffset) {
  10955. gl.enable(gl.POLYGON_OFFSET_FILL);
  10956. gl.polygonOffset(this.zOffset, 0);
  10957. }
  10958. else {
  10959. gl.disable(gl.POLYGON_OFFSET_FILL);
  10960. }
  10961. this._isZOffsetDirty = false;
  10962. }
  10963. // Front face
  10964. if (this._isFrontFaceDirty) {
  10965. gl.frontFace(this.frontFace);
  10966. this._isFrontFaceDirty = false;
  10967. }
  10968. };
  10969. return _DepthCullingState;
  10970. }());
  10971. BABYLON._DepthCullingState = _DepthCullingState;
  10972. })(BABYLON || (BABYLON = {}));
  10973. //# sourceMappingURL=babylon.depthCullingState.js.map
  10974. var BABYLON;
  10975. (function (BABYLON) {
  10976. /**
  10977. * @hidden
  10978. **/
  10979. var _StencilState = /** @class */ (function () {
  10980. function _StencilState() {
  10981. this._isStencilTestDirty = false;
  10982. this._isStencilMaskDirty = false;
  10983. this._isStencilFuncDirty = false;
  10984. this._isStencilOpDirty = false;
  10985. this.reset();
  10986. }
  10987. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10988. get: function () {
  10989. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10995. get: function () {
  10996. return this._stencilFunc;
  10997. },
  10998. set: function (value) {
  10999. if (this._stencilFunc === value) {
  11000. return;
  11001. }
  11002. this._stencilFunc = value;
  11003. this._isStencilFuncDirty = true;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11009. get: function () {
  11010. return this._stencilFuncRef;
  11011. },
  11012. set: function (value) {
  11013. if (this._stencilFuncRef === value) {
  11014. return;
  11015. }
  11016. this._stencilFuncRef = value;
  11017. this._isStencilFuncDirty = true;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11023. get: function () {
  11024. return this._stencilFuncMask;
  11025. },
  11026. set: function (value) {
  11027. if (this._stencilFuncMask === value) {
  11028. return;
  11029. }
  11030. this._stencilFuncMask = value;
  11031. this._isStencilFuncDirty = true;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11037. get: function () {
  11038. return this._stencilOpStencilFail;
  11039. },
  11040. set: function (value) {
  11041. if (this._stencilOpStencilFail === value) {
  11042. return;
  11043. }
  11044. this._stencilOpStencilFail = value;
  11045. this._isStencilOpDirty = true;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11051. get: function () {
  11052. return this._stencilOpDepthFail;
  11053. },
  11054. set: function (value) {
  11055. if (this._stencilOpDepthFail === value) {
  11056. return;
  11057. }
  11058. this._stencilOpDepthFail = value;
  11059. this._isStencilOpDirty = true;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11065. get: function () {
  11066. return this._stencilOpStencilDepthPass;
  11067. },
  11068. set: function (value) {
  11069. if (this._stencilOpStencilDepthPass === value) {
  11070. return;
  11071. }
  11072. this._stencilOpStencilDepthPass = value;
  11073. this._isStencilOpDirty = true;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11079. get: function () {
  11080. return this._stencilMask;
  11081. },
  11082. set: function (value) {
  11083. if (this._stencilMask === value) {
  11084. return;
  11085. }
  11086. this._stencilMask = value;
  11087. this._isStencilMaskDirty = true;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11093. get: function () {
  11094. return this._stencilTest;
  11095. },
  11096. set: function (value) {
  11097. if (this._stencilTest === value) {
  11098. return;
  11099. }
  11100. this._stencilTest = value;
  11101. this._isStencilTestDirty = true;
  11102. },
  11103. enumerable: true,
  11104. configurable: true
  11105. });
  11106. _StencilState.prototype.reset = function () {
  11107. this._stencilTest = false;
  11108. this._stencilMask = 0xFF;
  11109. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11110. this._stencilFuncRef = 1;
  11111. this._stencilFuncMask = 0xFF;
  11112. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11113. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11114. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11115. this._isStencilTestDirty = true;
  11116. this._isStencilMaskDirty = true;
  11117. this._isStencilFuncDirty = true;
  11118. this._isStencilOpDirty = true;
  11119. };
  11120. _StencilState.prototype.apply = function (gl) {
  11121. if (!this.isDirty) {
  11122. return;
  11123. }
  11124. // Stencil test
  11125. if (this._isStencilTestDirty) {
  11126. if (this.stencilTest) {
  11127. gl.enable(gl.STENCIL_TEST);
  11128. }
  11129. else {
  11130. gl.disable(gl.STENCIL_TEST);
  11131. }
  11132. this._isStencilTestDirty = false;
  11133. }
  11134. // Stencil mask
  11135. if (this._isStencilMaskDirty) {
  11136. gl.stencilMask(this.stencilMask);
  11137. this._isStencilMaskDirty = false;
  11138. }
  11139. // Stencil func
  11140. if (this._isStencilFuncDirty) {
  11141. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11142. this._isStencilFuncDirty = false;
  11143. }
  11144. // Stencil op
  11145. if (this._isStencilOpDirty) {
  11146. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11147. this._isStencilOpDirty = false;
  11148. }
  11149. };
  11150. return _StencilState;
  11151. }());
  11152. BABYLON._StencilState = _StencilState;
  11153. })(BABYLON || (BABYLON = {}));
  11154. //# sourceMappingURL=babylon.stencilState.js.map
  11155. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11156. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11157. s = arguments[i];
  11158. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11159. t[p] = s[p];
  11160. }
  11161. return t;
  11162. };
  11163. var BABYLON;
  11164. (function (BABYLON) {
  11165. /**
  11166. * Keeps track of all the buffer info used in engine.
  11167. */
  11168. var BufferPointer = /** @class */ (function () {
  11169. function BufferPointer() {
  11170. }
  11171. return BufferPointer;
  11172. }());
  11173. /**
  11174. * Interface for attribute information associated with buffer instanciation
  11175. */
  11176. var InstancingAttributeInfo = /** @class */ (function () {
  11177. function InstancingAttributeInfo() {
  11178. }
  11179. return InstancingAttributeInfo;
  11180. }());
  11181. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11182. /**
  11183. * Define options used to create a render target texture
  11184. */
  11185. var RenderTargetCreationOptions = /** @class */ (function () {
  11186. function RenderTargetCreationOptions() {
  11187. }
  11188. return RenderTargetCreationOptions;
  11189. }());
  11190. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11191. /**
  11192. * Define options used to create a depth texture
  11193. */
  11194. var DepthTextureCreationOptions = /** @class */ (function () {
  11195. function DepthTextureCreationOptions() {
  11196. }
  11197. return DepthTextureCreationOptions;
  11198. }());
  11199. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11200. /**
  11201. * Class used to describe the capabilities of the engine relatively to the current browser
  11202. */
  11203. var EngineCapabilities = /** @class */ (function () {
  11204. function EngineCapabilities() {
  11205. }
  11206. return EngineCapabilities;
  11207. }());
  11208. BABYLON.EngineCapabilities = EngineCapabilities;
  11209. /**
  11210. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11211. */
  11212. var Engine = /** @class */ (function () {
  11213. /**
  11214. * Creates a new engine
  11215. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11216. * @param antialias defines enable antialiasing (default: false)
  11217. * @param options defines further options to be sent to the getContext() function
  11218. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11219. */
  11220. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11221. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11222. var _this = this;
  11223. // Public members
  11224. /**
  11225. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11226. */
  11227. this.forcePOTTextures = false;
  11228. /**
  11229. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11230. */
  11231. this.isFullscreen = false;
  11232. /**
  11233. * Gets a boolean indicating if the pointer is currently locked
  11234. */
  11235. this.isPointerLock = false;
  11236. /**
  11237. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11238. */
  11239. this.cullBackFaces = true;
  11240. /**
  11241. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11242. */
  11243. this.renderEvenInBackground = true;
  11244. /**
  11245. * Gets or sets a boolean indicating that cache can be kept between frames
  11246. */
  11247. this.preventCacheWipeBetweenFrames = false;
  11248. /**
  11249. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11250. **/
  11251. this.enableOfflineSupport = false;
  11252. /**
  11253. * 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)
  11254. **/
  11255. this.disableManifestCheck = false;
  11256. /**
  11257. * Gets the list of created scenes
  11258. */
  11259. this.scenes = new Array();
  11260. /**
  11261. * Gets the list of created postprocesses
  11262. */
  11263. this.postProcesses = new Array();
  11264. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11265. this.validateShaderPrograms = false;
  11266. // Observables
  11267. /**
  11268. * Observable event triggered each time the rendering canvas is resized
  11269. */
  11270. this.onResizeObservable = new BABYLON.Observable();
  11271. /**
  11272. * Observable event triggered each time the canvas loses focus
  11273. */
  11274. this.onCanvasBlurObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable event triggered each time the canvas gains focus
  11277. */
  11278. this.onCanvasFocusObservable = new BABYLON.Observable();
  11279. /**
  11280. * Observable event triggered each time the canvas receives pointerout event
  11281. */
  11282. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11283. /**
  11284. * Observable event triggered before each texture is initialized
  11285. */
  11286. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11287. //WebVR
  11288. this._vrDisplay = undefined;
  11289. this._vrSupported = false;
  11290. this._vrExclusivePointerMode = false;
  11291. // Uniform buffers list
  11292. /**
  11293. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11294. */
  11295. this.disableUniformBuffers = false;
  11296. /** @hidden */
  11297. this._uniformBuffers = new Array();
  11298. // Observables
  11299. /**
  11300. * Observable raised when the engine begins a new frame
  11301. */
  11302. this.onBeginFrameObservable = new BABYLON.Observable();
  11303. /**
  11304. * Observable raised when the engine ends the current frame
  11305. */
  11306. this.onEndFrameObservable = new BABYLON.Observable();
  11307. /**
  11308. * Observable raised when the engine is about to compile a shader
  11309. */
  11310. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11311. /**
  11312. * Observable raised when the engine has jsut compiled a shader
  11313. */
  11314. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11315. this._windowIsBackground = false;
  11316. this._webGLVersion = 1.0;
  11317. /** @hidden */
  11318. this._badOS = false;
  11319. /** @hidden */
  11320. this._badDesktopOS = false;
  11321. /**
  11322. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11323. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11324. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11325. */
  11326. this.disableTextureBindingOptimization = false;
  11327. /**
  11328. * Observable signaled when VR display mode changes
  11329. */
  11330. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11331. /**
  11332. * Observable signaled when VR request present is complete
  11333. */
  11334. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11335. /**
  11336. * Observable signaled when VR request present starts
  11337. */
  11338. this.onVRRequestPresentStart = new BABYLON.Observable();
  11339. this._colorWrite = true;
  11340. /** @hidden */
  11341. this._drawCalls = new BABYLON.PerfCounter();
  11342. /** @hidden */
  11343. this._textureCollisions = new BABYLON.PerfCounter();
  11344. this._renderingQueueLaunched = false;
  11345. this._activeRenderLoops = new Array();
  11346. // Deterministic lockstepMaxSteps
  11347. this._deterministicLockstep = false;
  11348. this._lockstepMaxSteps = 4;
  11349. // Lost context
  11350. /**
  11351. * Observable signaled when a context lost event is raised
  11352. */
  11353. this.onContextLostObservable = new BABYLON.Observable();
  11354. /**
  11355. * Observable signaled when a context restored event is raised
  11356. */
  11357. this.onContextRestoredObservable = new BABYLON.Observable();
  11358. this._contextWasLost = false;
  11359. this._doNotHandleContextLost = false;
  11360. // FPS
  11361. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11362. this._fps = 60;
  11363. this._deltaTime = 0;
  11364. /**
  11365. * Turn this value on if you want to pause FPS computation when in background
  11366. */
  11367. this.disablePerformanceMonitorInBackground = false;
  11368. // States
  11369. /** @hidden */
  11370. this._depthCullingState = new BABYLON._DepthCullingState();
  11371. /** @hidden */
  11372. this._stencilState = new BABYLON._StencilState();
  11373. /** @hidden */
  11374. this._alphaState = new BABYLON._AlphaState();
  11375. /** @hidden */
  11376. this._alphaMode = Engine.ALPHA_DISABLE;
  11377. // Cache
  11378. this._internalTexturesCache = new Array();
  11379. /** @hidden */
  11380. this._activeChannel = 0;
  11381. this._currentTextureChannel = -1;
  11382. /** @hidden */
  11383. this._boundTexturesCache = {};
  11384. this._compiledEffects = {};
  11385. this._vertexAttribArraysEnabled = [];
  11386. this._uintIndicesCurrentlySet = false;
  11387. this._currentBoundBuffer = new Array();
  11388. /** @hidden */
  11389. this._currentFramebuffer = null;
  11390. this._currentBufferPointers = new Array();
  11391. this._currentInstanceLocations = new Array();
  11392. this._currentInstanceBuffers = new Array();
  11393. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11394. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11395. this._vaoRecordInProgress = false;
  11396. this._mustWipeVertexAttributes = false;
  11397. this._nextFreeTextureSlots = new Array();
  11398. this._maxSimultaneousTextures = 0;
  11399. this._activeRequests = new Array();
  11400. // Hardware supported Compressed Textures
  11401. this._texturesSupported = new Array();
  11402. /**
  11403. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11404. */
  11405. this.premultipliedAlpha = true;
  11406. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11407. this._onVRFullScreenTriggered = function () {
  11408. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11409. //get the old size before we change
  11410. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11411. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11412. //get the width and height, change the render size
  11413. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11414. _this.setHardwareScalingLevel(1);
  11415. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11416. }
  11417. else {
  11418. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11419. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11420. }
  11421. };
  11422. this._unpackFlipYCached = null;
  11423. this._boundUniforms = {};
  11424. // Register promises
  11425. BABYLON.PromisePolyfill.Apply();
  11426. var canvas = null;
  11427. Engine.Instances.push(this);
  11428. if (!canvasOrContext) {
  11429. return;
  11430. }
  11431. options = options || {};
  11432. if (canvasOrContext.getContext) {
  11433. canvas = canvasOrContext;
  11434. this._renderingCanvas = canvas;
  11435. if (antialias != null) {
  11436. options.antialias = antialias;
  11437. }
  11438. if (options.deterministicLockstep === undefined) {
  11439. options.deterministicLockstep = false;
  11440. }
  11441. if (options.lockstepMaxSteps === undefined) {
  11442. options.lockstepMaxSteps = 4;
  11443. }
  11444. if (options.preserveDrawingBuffer === undefined) {
  11445. options.preserveDrawingBuffer = false;
  11446. }
  11447. if (options.audioEngine === undefined) {
  11448. options.audioEngine = true;
  11449. }
  11450. if (options.stencil === undefined) {
  11451. options.stencil = true;
  11452. }
  11453. if (options.premultipliedAlpha === false) {
  11454. this.premultipliedAlpha = false;
  11455. }
  11456. this._deterministicLockstep = options.deterministicLockstep;
  11457. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11458. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11459. // Exceptions
  11460. if (navigator && navigator.userAgent) {
  11461. var ua = navigator.userAgent;
  11462. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11463. var exception = _a[_i];
  11464. var key = exception.key;
  11465. var targets = exception.targets;
  11466. if (ua.indexOf(key) > -1) {
  11467. if (exception.capture && exception.captureConstraint) {
  11468. var capture = exception.capture;
  11469. var constraint = exception.captureConstraint;
  11470. var regex = new RegExp(capture);
  11471. var matches = regex.exec(ua);
  11472. if (matches && matches.length > 0) {
  11473. var capturedValue = parseInt(matches[matches.length - 1]);
  11474. if (capturedValue >= constraint) {
  11475. continue;
  11476. }
  11477. }
  11478. }
  11479. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11480. var target = targets_1[_b];
  11481. switch (target) {
  11482. case "uniformBuffer":
  11483. this.disableUniformBuffers = true;
  11484. break;
  11485. case "textureBindingOptimization":
  11486. this.disableTextureBindingOptimization = true;
  11487. break;
  11488. }
  11489. }
  11490. }
  11491. }
  11492. }
  11493. // GL
  11494. if (!options.disableWebGL2Support) {
  11495. try {
  11496. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11497. if (this._gl) {
  11498. this._webGLVersion = 2.0;
  11499. }
  11500. }
  11501. catch (e) {
  11502. // Do nothing
  11503. }
  11504. }
  11505. if (!this._gl) {
  11506. if (!canvas) {
  11507. throw new Error("The provided canvas is null or undefined.");
  11508. }
  11509. try {
  11510. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11511. }
  11512. catch (e) {
  11513. throw new Error("WebGL not supported");
  11514. }
  11515. }
  11516. if (!this._gl) {
  11517. throw new Error("WebGL not supported");
  11518. }
  11519. this._onCanvasFocus = function () {
  11520. _this.onCanvasFocusObservable.notifyObservers(_this);
  11521. };
  11522. this._onCanvasBlur = function () {
  11523. _this.onCanvasBlurObservable.notifyObservers(_this);
  11524. };
  11525. canvas.addEventListener("focus", this._onCanvasFocus);
  11526. canvas.addEventListener("blur", this._onCanvasBlur);
  11527. this._onBlur = function () {
  11528. if (_this.disablePerformanceMonitorInBackground) {
  11529. _this._performanceMonitor.disable();
  11530. }
  11531. _this._windowIsBackground = true;
  11532. };
  11533. this._onFocus = function () {
  11534. if (_this.disablePerformanceMonitorInBackground) {
  11535. _this._performanceMonitor.enable();
  11536. }
  11537. _this._windowIsBackground = false;
  11538. };
  11539. this._onCanvasPointerOut = function (ev) {
  11540. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11541. };
  11542. window.addEventListener("blur", this._onBlur);
  11543. window.addEventListener("focus", this._onFocus);
  11544. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11545. // Context lost
  11546. if (!this._doNotHandleContextLost) {
  11547. this._onContextLost = function (evt) {
  11548. evt.preventDefault();
  11549. _this._contextWasLost = true;
  11550. BABYLON.Tools.Warn("WebGL context lost.");
  11551. _this.onContextLostObservable.notifyObservers(_this);
  11552. };
  11553. this._onContextRestored = function (evt) {
  11554. // Adding a timeout to avoid race condition at browser level
  11555. setTimeout(function () {
  11556. // Rebuild gl context
  11557. _this._initGLContext();
  11558. // Rebuild effects
  11559. _this._rebuildEffects();
  11560. // Rebuild textures
  11561. _this._rebuildInternalTextures();
  11562. // Rebuild buffers
  11563. _this._rebuildBuffers();
  11564. // Cache
  11565. _this.wipeCaches(true);
  11566. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11567. _this.onContextRestoredObservable.notifyObservers(_this);
  11568. _this._contextWasLost = false;
  11569. }, 0);
  11570. };
  11571. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11572. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11573. }
  11574. }
  11575. else {
  11576. this._gl = canvasOrContext;
  11577. this._renderingCanvas = this._gl.canvas;
  11578. if (this._gl.renderbufferStorageMultisample) {
  11579. this._webGLVersion = 2.0;
  11580. }
  11581. options.stencil = this._gl.getContextAttributes().stencil;
  11582. }
  11583. // Viewport
  11584. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11585. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11586. this.resize();
  11587. this._isStencilEnable = options.stencil ? true : false;
  11588. this._initGLContext();
  11589. if (canvas) {
  11590. // Fullscreen
  11591. this._onFullscreenChange = function () {
  11592. if (document.fullscreen !== undefined) {
  11593. _this.isFullscreen = document.fullscreen;
  11594. }
  11595. else if (document.mozFullScreen !== undefined) {
  11596. _this.isFullscreen = document.mozFullScreen;
  11597. }
  11598. else if (document.webkitIsFullScreen !== undefined) {
  11599. _this.isFullscreen = document.webkitIsFullScreen;
  11600. }
  11601. else if (document.msIsFullScreen !== undefined) {
  11602. _this.isFullscreen = document.msIsFullScreen;
  11603. }
  11604. // Pointer lock
  11605. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11606. canvas.requestPointerLock = canvas.requestPointerLock ||
  11607. canvas.msRequestPointerLock ||
  11608. canvas.mozRequestPointerLock ||
  11609. canvas.webkitRequestPointerLock;
  11610. if (canvas.requestPointerLock) {
  11611. canvas.requestPointerLock();
  11612. }
  11613. }
  11614. };
  11615. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11616. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11617. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11618. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11619. // Pointer lock
  11620. this._onPointerLockChange = function () {
  11621. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11622. document.webkitPointerLockElement === canvas ||
  11623. document.msPointerLockElement === canvas ||
  11624. document.pointerLockElement === canvas);
  11625. };
  11626. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11627. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11628. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11629. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11630. this._onVRDisplayPointerRestricted = function () {
  11631. if (canvas) {
  11632. canvas.requestPointerLock();
  11633. }
  11634. };
  11635. this._onVRDisplayPointerUnrestricted = function () {
  11636. document.exitPointerLock();
  11637. };
  11638. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11639. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11640. }
  11641. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11642. Engine.audioEngine = new BABYLON.AudioEngine();
  11643. }
  11644. // Prepare buffer pointers
  11645. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11646. this._currentBufferPointers[i] = new BufferPointer();
  11647. }
  11648. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11649. // Load WebVR Devices
  11650. if (options.autoEnableWebVR) {
  11651. this.initWebVR();
  11652. }
  11653. // Detect if we are running on a faulty buggy OS.
  11654. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11655. // Detect if we are running on a faulty buggy desktop OS.
  11656. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11657. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11658. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11659. }
  11660. Object.defineProperty(Engine, "LastCreatedEngine", {
  11661. /**
  11662. * Gets the latest created engine
  11663. */
  11664. get: function () {
  11665. if (Engine.Instances.length === 0) {
  11666. return null;
  11667. }
  11668. return Engine.Instances[Engine.Instances.length - 1];
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(Engine, "LastCreatedScene", {
  11674. /**
  11675. * Gets the latest created scene
  11676. */
  11677. get: function () {
  11678. var lastCreatedEngine = Engine.LastCreatedEngine;
  11679. if (!lastCreatedEngine) {
  11680. return null;
  11681. }
  11682. if (lastCreatedEngine.scenes.length === 0) {
  11683. return null;
  11684. }
  11685. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. /**
  11691. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11692. * @param flag defines which part of the materials must be marked as dirty
  11693. * @param predicate defines a predicate used to filter which materials should be affected
  11694. */
  11695. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11696. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11697. var engine = Engine.Instances[engineIndex];
  11698. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11699. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11700. }
  11701. }
  11702. };
  11703. Object.defineProperty(Engine, "Version", {
  11704. /**
  11705. * Returns the current version of the framework
  11706. */
  11707. get: function () {
  11708. return "3.3.0-alpha.13";
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11714. /**
  11715. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11716. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11717. */
  11718. get: function () {
  11719. return this._vrExclusivePointerMode;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11725. /**
  11726. * Gets a boolean indicating that the engine supports uniform buffers
  11727. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11728. */
  11729. get: function () {
  11730. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11736. /**
  11737. * Gets a boolean indicating that only power of 2 textures are supported
  11738. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11739. */
  11740. get: function () {
  11741. return this._webGLVersion < 2 || this.forcePOTTextures;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11747. /**
  11748. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11749. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11750. */
  11751. get: function () {
  11752. return this._doNotHandleContextLost;
  11753. },
  11754. set: function (value) {
  11755. this._doNotHandleContextLost = value;
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11761. /**
  11762. * Gets the performance monitor attached to this engine
  11763. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11764. */
  11765. get: function () {
  11766. return this._performanceMonitor;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11772. /**
  11773. * Gets the list of texture formats supported
  11774. */
  11775. get: function () {
  11776. return this._texturesSupported;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11782. /**
  11783. * Gets the list of texture formats in use
  11784. */
  11785. get: function () {
  11786. return this._textureFormatInUse;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine.prototype, "currentViewport", {
  11792. /**
  11793. * Gets the current viewport
  11794. */
  11795. get: function () {
  11796. return this._cachedViewport;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11802. /**
  11803. * Gets the default empty texture
  11804. */
  11805. get: function () {
  11806. if (!this._emptyTexture) {
  11807. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11808. }
  11809. return this._emptyTexture;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11815. /**
  11816. * Gets the default empty 3D texture
  11817. */
  11818. get: function () {
  11819. if (!this._emptyTexture3D) {
  11820. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11821. }
  11822. return this._emptyTexture3D;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11828. /**
  11829. * Gets the default empty cube texture
  11830. */
  11831. get: function () {
  11832. if (!this._emptyCubeTexture) {
  11833. var faceData = new Uint8Array(4);
  11834. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11835. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11836. }
  11837. return this._emptyCubeTexture;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Engine.prototype._rebuildInternalTextures = function () {
  11843. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11844. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11845. var internalTexture = currentState_1[_i];
  11846. internalTexture._rebuild();
  11847. }
  11848. };
  11849. Engine.prototype._rebuildEffects = function () {
  11850. for (var key in this._compiledEffects) {
  11851. var effect = this._compiledEffects[key];
  11852. effect._prepareEffect();
  11853. }
  11854. BABYLON.Effect.ResetCache();
  11855. };
  11856. Engine.prototype._rebuildBuffers = function () {
  11857. // Index / Vertex
  11858. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11859. var scene = _a[_i];
  11860. scene.resetCachedMaterial();
  11861. scene._rebuildGeometries();
  11862. scene._rebuildTextures();
  11863. }
  11864. // Uniforms
  11865. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11866. var uniformBuffer = _c[_b];
  11867. uniformBuffer._rebuild();
  11868. }
  11869. };
  11870. Engine.prototype._initGLContext = function () {
  11871. // Caps
  11872. this._caps = new EngineCapabilities();
  11873. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11874. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11875. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11876. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11877. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11878. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11879. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11880. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11881. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11882. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11883. // Infos
  11884. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11885. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11886. if (rendererInfo != null) {
  11887. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11888. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11889. }
  11890. if (!this._glVendor) {
  11891. this._glVendor = "Unknown vendor";
  11892. }
  11893. if (!this._glRenderer) {
  11894. this._glRenderer = "Unknown renderer";
  11895. }
  11896. // Constants
  11897. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11898. if (this._gl.RGBA16F !== 0x881A) {
  11899. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11900. }
  11901. if (this._gl.RGBA32F !== 0x8814) {
  11902. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11903. }
  11904. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11905. this._gl.DEPTH24_STENCIL8 = 35056;
  11906. }
  11907. // Extensions
  11908. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11909. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11910. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11911. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11912. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11913. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11914. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11915. 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');
  11916. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11917. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11918. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11919. this._caps.highPrecisionShaderSupported = true;
  11920. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11921. if (this._caps.timerQuery) {
  11922. if (this._webGLVersion === 1) {
  11923. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11924. }
  11925. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11926. }
  11927. // Checks if some of the format renders first to allow the use of webgl inspector.
  11928. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11929. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11930. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11931. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11932. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11933. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11934. if (this._webGLVersion > 1) {
  11935. this._gl.HALF_FLOAT_OES = 0x140B;
  11936. }
  11937. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11938. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11939. // Draw buffers
  11940. if (this._webGLVersion > 1) {
  11941. this._caps.drawBuffersExtension = true;
  11942. }
  11943. else {
  11944. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11945. if (drawBuffersExtension !== null) {
  11946. this._caps.drawBuffersExtension = true;
  11947. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11948. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11949. for (var i = 0; i < 16; i++) {
  11950. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11951. }
  11952. }
  11953. else {
  11954. this._caps.drawBuffersExtension = false;
  11955. }
  11956. }
  11957. // Depth Texture
  11958. if (this._webGLVersion > 1) {
  11959. this._caps.depthTextureExtension = true;
  11960. }
  11961. else {
  11962. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11963. if (depthTextureExtension != null) {
  11964. this._caps.depthTextureExtension = true;
  11965. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11966. }
  11967. }
  11968. // Vertex array object
  11969. if (this._webGLVersion > 1) {
  11970. this._caps.vertexArrayObject = true;
  11971. }
  11972. else {
  11973. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11974. if (vertexArrayObjectExtension != null) {
  11975. this._caps.vertexArrayObject = true;
  11976. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11977. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11978. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11979. }
  11980. else {
  11981. this._caps.vertexArrayObject = false;
  11982. }
  11983. }
  11984. // Instances count
  11985. if (this._webGLVersion > 1) {
  11986. this._caps.instancedArrays = true;
  11987. }
  11988. else {
  11989. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11990. if (instanceExtension != null) {
  11991. this._caps.instancedArrays = true;
  11992. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11993. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11994. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11995. }
  11996. else {
  11997. this._caps.instancedArrays = false;
  11998. }
  11999. }
  12000. // Intelligently add supported compressed formats in order to check for.
  12001. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12002. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12003. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12004. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12005. if (this._caps.astc)
  12006. this.texturesSupported.push('-astc.ktx');
  12007. if (this._caps.s3tc)
  12008. this.texturesSupported.push('-dxt.ktx');
  12009. if (this._caps.pvrtc)
  12010. this.texturesSupported.push('-pvrtc.ktx');
  12011. if (this._caps.etc2)
  12012. this.texturesSupported.push('-etc2.ktx');
  12013. if (this._caps.etc1)
  12014. this.texturesSupported.push('-etc1.ktx');
  12015. if (this._gl.getShaderPrecisionFormat) {
  12016. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12017. if (highp) {
  12018. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12019. }
  12020. }
  12021. // Depth buffer
  12022. this.setDepthBuffer(true);
  12023. this.setDepthFunctionToLessOrEqual();
  12024. this.setDepthWrite(true);
  12025. // Texture maps
  12026. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12027. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12028. this._nextFreeTextureSlots.push(slot);
  12029. }
  12030. };
  12031. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12032. /**
  12033. * Gets version of the current webGL context
  12034. */
  12035. get: function () {
  12036. return this._webGLVersion;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12042. /**
  12043. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12044. */
  12045. get: function () {
  12046. return this._isStencilEnable;
  12047. },
  12048. enumerable: true,
  12049. configurable: true
  12050. });
  12051. Engine.prototype._prepareWorkingCanvas = function () {
  12052. if (this._workingCanvas) {
  12053. return;
  12054. }
  12055. this._workingCanvas = document.createElement("canvas");
  12056. var context = this._workingCanvas.getContext("2d");
  12057. if (context) {
  12058. this._workingContext = context;
  12059. }
  12060. };
  12061. /**
  12062. * Reset the texture cache to empty state
  12063. */
  12064. Engine.prototype.resetTextureCache = function () {
  12065. for (var key in this._boundTexturesCache) {
  12066. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12067. continue;
  12068. }
  12069. var boundTexture = this._boundTexturesCache[key];
  12070. if (boundTexture) {
  12071. this._removeDesignatedSlot(boundTexture);
  12072. }
  12073. this._boundTexturesCache[key] = null;
  12074. }
  12075. if (!this.disableTextureBindingOptimization) {
  12076. this._nextFreeTextureSlots = [];
  12077. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12078. this._nextFreeTextureSlots.push(slot);
  12079. }
  12080. }
  12081. this._currentTextureChannel = -1;
  12082. };
  12083. /**
  12084. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12085. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12086. * @returns true if engine is in deterministic lock step mode
  12087. */
  12088. Engine.prototype.isDeterministicLockStep = function () {
  12089. return this._deterministicLockstep;
  12090. };
  12091. /**
  12092. * Gets the max steps when engine is running in deterministic lock step
  12093. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12094. * @returns the max steps
  12095. */
  12096. Engine.prototype.getLockstepMaxSteps = function () {
  12097. return this._lockstepMaxSteps;
  12098. };
  12099. /**
  12100. * Gets an object containing information about the current webGL context
  12101. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12102. */
  12103. Engine.prototype.getGlInfo = function () {
  12104. return {
  12105. vendor: this._glVendor,
  12106. renderer: this._glRenderer,
  12107. version: this._glVersion
  12108. };
  12109. };
  12110. /**
  12111. * Gets current aspect ratio
  12112. * @param camera defines the camera to use to get the aspect ratio
  12113. * @param useScreen defines if screen size must be used (or the current render target if any)
  12114. * @returns a number defining the aspect ratio
  12115. */
  12116. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12117. if (useScreen === void 0) { useScreen = false; }
  12118. var viewport = camera.viewport;
  12119. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12120. };
  12121. /**
  12122. * Gets current screen aspect ratio
  12123. * @returns a number defining the aspect ratio
  12124. */
  12125. Engine.prototype.getScreenAspectRatio = function () {
  12126. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12127. };
  12128. /**
  12129. * Gets the current render width
  12130. * @param useScreen defines if screen size must be used (or the current render target if any)
  12131. * @returns a number defining the current render width
  12132. */
  12133. Engine.prototype.getRenderWidth = function (useScreen) {
  12134. if (useScreen === void 0) { useScreen = false; }
  12135. if (!useScreen && this._currentRenderTarget) {
  12136. return this._currentRenderTarget.width;
  12137. }
  12138. return this._gl.drawingBufferWidth;
  12139. };
  12140. /**
  12141. * Gets the current render height
  12142. * @param useScreen defines if screen size must be used (or the current render target if any)
  12143. * @returns a number defining the current render height
  12144. */
  12145. Engine.prototype.getRenderHeight = function (useScreen) {
  12146. if (useScreen === void 0) { useScreen = false; }
  12147. if (!useScreen && this._currentRenderTarget) {
  12148. return this._currentRenderTarget.height;
  12149. }
  12150. return this._gl.drawingBufferHeight;
  12151. };
  12152. /**
  12153. * Gets the HTML canvas attached with the current webGL context
  12154. * @returns a HTML canvas
  12155. */
  12156. Engine.prototype.getRenderingCanvas = function () {
  12157. return this._renderingCanvas;
  12158. };
  12159. /**
  12160. * Gets the client rect of the HTML canvas attached with the current webGL context
  12161. * @returns a client rectanglee
  12162. */
  12163. Engine.prototype.getRenderingCanvasClientRect = function () {
  12164. if (!this._renderingCanvas) {
  12165. return null;
  12166. }
  12167. return this._renderingCanvas.getBoundingClientRect();
  12168. };
  12169. /**
  12170. * Defines the hardware scaling level.
  12171. * By default the hardware scaling level is computed from the window device ratio.
  12172. * 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.
  12173. * @param level defines the level to use
  12174. */
  12175. Engine.prototype.setHardwareScalingLevel = function (level) {
  12176. this._hardwareScalingLevel = level;
  12177. this.resize();
  12178. };
  12179. /**
  12180. * Gets the current hardware scaling level.
  12181. * By default the hardware scaling level is computed from the window device ratio.
  12182. * 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.
  12183. * @returns a number indicating the current hardware scaling level
  12184. */
  12185. Engine.prototype.getHardwareScalingLevel = function () {
  12186. return this._hardwareScalingLevel;
  12187. };
  12188. /**
  12189. * Gets the list of loaded textures
  12190. * @returns an array containing all loaded textures
  12191. */
  12192. Engine.prototype.getLoadedTexturesCache = function () {
  12193. return this._internalTexturesCache;
  12194. };
  12195. /**
  12196. * Gets the object containing all engine capabilities
  12197. * @returns the EngineCapabilities object
  12198. */
  12199. Engine.prototype.getCaps = function () {
  12200. return this._caps;
  12201. };
  12202. Object.defineProperty(Engine.prototype, "drawCalls", {
  12203. /** @hidden */
  12204. get: function () {
  12205. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12206. return 0;
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12212. /** @hidden */
  12213. get: function () {
  12214. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12215. return null;
  12216. },
  12217. enumerable: true,
  12218. configurable: true
  12219. });
  12220. /**
  12221. * Gets the current depth function
  12222. * @returns a number defining the depth function
  12223. */
  12224. Engine.prototype.getDepthFunction = function () {
  12225. return this._depthCullingState.depthFunc;
  12226. };
  12227. /**
  12228. * Sets the current depth function
  12229. * @param depthFunc defines the function to use
  12230. */
  12231. Engine.prototype.setDepthFunction = function (depthFunc) {
  12232. this._depthCullingState.depthFunc = depthFunc;
  12233. };
  12234. /**
  12235. * Sets the current depth function to GREATER
  12236. */
  12237. Engine.prototype.setDepthFunctionToGreater = function () {
  12238. this._depthCullingState.depthFunc = this._gl.GREATER;
  12239. };
  12240. /**
  12241. * Sets the current depth function to GEQUAL
  12242. */
  12243. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12244. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12245. };
  12246. /**
  12247. * Sets the current depth function to LESS
  12248. */
  12249. Engine.prototype.setDepthFunctionToLess = function () {
  12250. this._depthCullingState.depthFunc = this._gl.LESS;
  12251. };
  12252. /**
  12253. * Sets the current depth function to LEQUAL
  12254. */
  12255. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12256. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12257. };
  12258. /**
  12259. * Gets a boolean indicating if stencil buffer is enabled
  12260. * @returns the current stencil buffer state
  12261. */
  12262. Engine.prototype.getStencilBuffer = function () {
  12263. return this._stencilState.stencilTest;
  12264. };
  12265. /**
  12266. * Enable or disable the stencil buffer
  12267. * @param enable defines if the stencil buffer must be enabled or disabled
  12268. */
  12269. Engine.prototype.setStencilBuffer = function (enable) {
  12270. this._stencilState.stencilTest = enable;
  12271. };
  12272. /**
  12273. * Gets the current stencil mask
  12274. * @returns a number defining the new stencil mask to use
  12275. */
  12276. Engine.prototype.getStencilMask = function () {
  12277. return this._stencilState.stencilMask;
  12278. };
  12279. /**
  12280. * Sets the current stencil mask
  12281. * @param mask defines the new stencil mask to use
  12282. */
  12283. Engine.prototype.setStencilMask = function (mask) {
  12284. this._stencilState.stencilMask = mask;
  12285. };
  12286. /**
  12287. * Gets the current stencil function
  12288. * @returns a number defining the stencil function to use
  12289. */
  12290. Engine.prototype.getStencilFunction = function () {
  12291. return this._stencilState.stencilFunc;
  12292. };
  12293. /**
  12294. * Gets the current stencil reference value
  12295. * @returns a number defining the stencil reference value to use
  12296. */
  12297. Engine.prototype.getStencilFunctionReference = function () {
  12298. return this._stencilState.stencilFuncRef;
  12299. };
  12300. /**
  12301. * Gets the current stencil mask
  12302. * @returns a number defining the stencil mask to use
  12303. */
  12304. Engine.prototype.getStencilFunctionMask = function () {
  12305. return this._stencilState.stencilFuncMask;
  12306. };
  12307. /**
  12308. * Sets the current stencil function
  12309. * @param stencilFunc defines the new stencil function to use
  12310. */
  12311. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12312. this._stencilState.stencilFunc = stencilFunc;
  12313. };
  12314. /**
  12315. * Sets the current stencil reference
  12316. * @param reference defines the new stencil reference to use
  12317. */
  12318. Engine.prototype.setStencilFunctionReference = function (reference) {
  12319. this._stencilState.stencilFuncRef = reference;
  12320. };
  12321. /**
  12322. * Sets the current stencil mask
  12323. * @param mask defines the new stencil mask to use
  12324. */
  12325. Engine.prototype.setStencilFunctionMask = function (mask) {
  12326. this._stencilState.stencilFuncMask = mask;
  12327. };
  12328. /**
  12329. * Gets the current stencil operation when stencil fails
  12330. * @returns a number defining stencil operation to use when stencil fails
  12331. */
  12332. Engine.prototype.getStencilOperationFail = function () {
  12333. return this._stencilState.stencilOpStencilFail;
  12334. };
  12335. /**
  12336. * Gets the current stencil operation when depth fails
  12337. * @returns a number defining stencil operation to use when depth fails
  12338. */
  12339. Engine.prototype.getStencilOperationDepthFail = function () {
  12340. return this._stencilState.stencilOpDepthFail;
  12341. };
  12342. /**
  12343. * Gets the current stencil operation when stencil passes
  12344. * @returns a number defining stencil operation to use when stencil passes
  12345. */
  12346. Engine.prototype.getStencilOperationPass = function () {
  12347. return this._stencilState.stencilOpStencilDepthPass;
  12348. };
  12349. /**
  12350. * Sets the stencil operation to use when stencil fails
  12351. * @param operation defines the stencil operation to use when stencil fails
  12352. */
  12353. Engine.prototype.setStencilOperationFail = function (operation) {
  12354. this._stencilState.stencilOpStencilFail = operation;
  12355. };
  12356. /**
  12357. * Sets the stencil operation to use when depth fails
  12358. * @param operation defines the stencil operation to use when depth fails
  12359. */
  12360. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12361. this._stencilState.stencilOpDepthFail = operation;
  12362. };
  12363. /**
  12364. * Sets the stencil operation to use when stencil passes
  12365. * @param operation defines the stencil operation to use when stencil passes
  12366. */
  12367. Engine.prototype.setStencilOperationPass = function (operation) {
  12368. this._stencilState.stencilOpStencilDepthPass = operation;
  12369. };
  12370. /**
  12371. * Sets a boolean indicating if the dithering state is enabled or disabled
  12372. * @param value defines the dithering state
  12373. */
  12374. Engine.prototype.setDitheringState = function (value) {
  12375. if (value) {
  12376. this._gl.enable(this._gl.DITHER);
  12377. }
  12378. else {
  12379. this._gl.disable(this._gl.DITHER);
  12380. }
  12381. };
  12382. /**
  12383. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12384. * @param value defines the rasterizer state
  12385. */
  12386. Engine.prototype.setRasterizerState = function (value) {
  12387. if (value) {
  12388. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12389. }
  12390. else {
  12391. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12392. }
  12393. };
  12394. /**
  12395. * stop executing a render loop function and remove it from the execution array
  12396. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12397. */
  12398. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12399. if (!renderFunction) {
  12400. this._activeRenderLoops = [];
  12401. return;
  12402. }
  12403. var index = this._activeRenderLoops.indexOf(renderFunction);
  12404. if (index >= 0) {
  12405. this._activeRenderLoops.splice(index, 1);
  12406. }
  12407. };
  12408. /** @hidden */
  12409. Engine.prototype._renderLoop = function () {
  12410. if (!this._contextWasLost) {
  12411. var shouldRender = true;
  12412. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12413. shouldRender = false;
  12414. }
  12415. if (shouldRender) {
  12416. // Start new frame
  12417. this.beginFrame();
  12418. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12419. var renderFunction = this._activeRenderLoops[index];
  12420. renderFunction();
  12421. }
  12422. // Present
  12423. this.endFrame();
  12424. }
  12425. }
  12426. if (this._activeRenderLoops.length > 0) {
  12427. // Register new frame
  12428. var requester = null;
  12429. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12430. requester = this._vrDisplay;
  12431. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12432. }
  12433. else {
  12434. this._renderingQueueLaunched = false;
  12435. }
  12436. };
  12437. /**
  12438. * Register and execute a render loop. The engine can have more than one render function
  12439. * @param renderFunction defines the function to continuously execute
  12440. */
  12441. Engine.prototype.runRenderLoop = function (renderFunction) {
  12442. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12443. return;
  12444. }
  12445. this._activeRenderLoops.push(renderFunction);
  12446. if (!this._renderingQueueLaunched) {
  12447. this._renderingQueueLaunched = true;
  12448. this._bindedRenderFunction = this._renderLoop.bind(this);
  12449. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12450. }
  12451. };
  12452. /**
  12453. * Toggle full screen mode
  12454. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12455. * @param options defines an option object to be sent to the requestFullscreen function
  12456. */
  12457. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12458. if (this.isFullscreen) {
  12459. BABYLON.Tools.ExitFullscreen();
  12460. }
  12461. else {
  12462. this._pointerLockRequested = requestPointerLock;
  12463. if (this._renderingCanvas) {
  12464. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12465. }
  12466. }
  12467. };
  12468. /**
  12469. * Clear the current render buffer or the current render target (if any is set up)
  12470. * @param color defines the color to use
  12471. * @param backBuffer defines if the back buffer must be cleared
  12472. * @param depth defines if the depth buffer must be cleared
  12473. * @param stencil defines if the stencil buffer must be cleared
  12474. */
  12475. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12476. if (stencil === void 0) { stencil = false; }
  12477. this.applyStates();
  12478. var mode = 0;
  12479. if (backBuffer && color) {
  12480. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12481. mode |= this._gl.COLOR_BUFFER_BIT;
  12482. }
  12483. if (depth) {
  12484. this._gl.clearDepth(1.0);
  12485. mode |= this._gl.DEPTH_BUFFER_BIT;
  12486. }
  12487. if (stencil) {
  12488. this._gl.clearStencil(0);
  12489. mode |= this._gl.STENCIL_BUFFER_BIT;
  12490. }
  12491. this._gl.clear(mode);
  12492. };
  12493. /**
  12494. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12495. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12496. * @param y defines the y-coordinate of the corner of the clear rectangle
  12497. * @param width defines the width of the clear rectangle
  12498. * @param height defines the height of the clear rectangle
  12499. * @param clearColor defines the clear color
  12500. */
  12501. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12502. var gl = this._gl;
  12503. // Save state
  12504. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12505. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12506. // Change state
  12507. gl.enable(gl.SCISSOR_TEST);
  12508. gl.scissor(x, y, width, height);
  12509. // Clear
  12510. this.clear(clearColor, true, true, true);
  12511. // Restore state
  12512. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12513. if (curScissor === true) {
  12514. gl.enable(gl.SCISSOR_TEST);
  12515. }
  12516. else {
  12517. gl.disable(gl.SCISSOR_TEST);
  12518. }
  12519. };
  12520. /** @hidden */
  12521. Engine.prototype._viewport = function (x, y, width, height) {
  12522. if (x !== this._viewportCached.x ||
  12523. y !== this._viewportCached.y ||
  12524. width !== this._viewportCached.z ||
  12525. height !== this._viewportCached.w) {
  12526. this._viewportCached.x = x;
  12527. this._viewportCached.y = y;
  12528. this._viewportCached.z = width;
  12529. this._viewportCached.w = height;
  12530. this._gl.viewport(x, y, width, height);
  12531. }
  12532. };
  12533. /**
  12534. * Set the WebGL's viewport
  12535. * @param viewport defines the viewport element to be used
  12536. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12537. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12538. */
  12539. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12540. var width = requiredWidth || this.getRenderWidth();
  12541. var height = requiredHeight || this.getRenderHeight();
  12542. var x = viewport.x || 0;
  12543. var y = viewport.y || 0;
  12544. this._cachedViewport = viewport;
  12545. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12546. };
  12547. /**
  12548. * Directly set the WebGL Viewport
  12549. * @param x defines the x coordinate of the viewport (in screen space)
  12550. * @param y defines the y coordinate of the viewport (in screen space)
  12551. * @param width defines the width of the viewport (in screen space)
  12552. * @param height defines the height of the viewport (in screen space)
  12553. * @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
  12554. */
  12555. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12556. var currentViewport = this._cachedViewport;
  12557. this._cachedViewport = null;
  12558. this._viewport(x, y, width, height);
  12559. return currentViewport;
  12560. };
  12561. /**
  12562. * Begin a new frame
  12563. */
  12564. Engine.prototype.beginFrame = function () {
  12565. this.onBeginFrameObservable.notifyObservers(this);
  12566. this._measureFps();
  12567. };
  12568. /**
  12569. * Enf the current frame
  12570. */
  12571. Engine.prototype.endFrame = function () {
  12572. // Force a flush in case we are using a bad OS.
  12573. if (this._badOS) {
  12574. this.flushFramebuffer();
  12575. }
  12576. // Submit frame to the vr device, if enabled
  12577. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12578. // TODO: We should only submit the frame if we read frameData successfully.
  12579. this._vrDisplay.submitFrame();
  12580. }
  12581. this.onEndFrameObservable.notifyObservers(this);
  12582. };
  12583. /**
  12584. * Resize the view according to the canvas' size
  12585. */
  12586. Engine.prototype.resize = function () {
  12587. // We're not resizing the size of the canvas while in VR mode & presenting
  12588. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12589. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12590. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12591. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12592. }
  12593. };
  12594. /**
  12595. * Force a specific size of the canvas
  12596. * @param width defines the new canvas' width
  12597. * @param height defines the new canvas' height
  12598. */
  12599. Engine.prototype.setSize = function (width, height) {
  12600. if (!this._renderingCanvas) {
  12601. return;
  12602. }
  12603. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12604. return;
  12605. }
  12606. this._renderingCanvas.width = width;
  12607. this._renderingCanvas.height = height;
  12608. for (var index = 0; index < this.scenes.length; index++) {
  12609. var scene = this.scenes[index];
  12610. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12611. var cam = scene.cameras[camIndex];
  12612. cam._currentRenderId = 0;
  12613. }
  12614. }
  12615. if (this.onResizeObservable.hasObservers) {
  12616. this.onResizeObservable.notifyObservers(this);
  12617. }
  12618. };
  12619. // WebVR functions
  12620. /**
  12621. * Gets a boolean indicating if a webVR device was detected
  12622. * @returns true if a webVR device was detected
  12623. */
  12624. Engine.prototype.isVRDevicePresent = function () {
  12625. return !!this._vrDisplay;
  12626. };
  12627. /**
  12628. * Gets the current webVR device
  12629. * @returns the current webVR device (or null)
  12630. */
  12631. Engine.prototype.getVRDevice = function () {
  12632. return this._vrDisplay;
  12633. };
  12634. /**
  12635. * Initializes a webVR display and starts listening to display change events
  12636. * The onVRDisplayChangedObservable will be notified upon these changes
  12637. * @returns The onVRDisplayChangedObservable
  12638. */
  12639. Engine.prototype.initWebVR = function () {
  12640. this.initWebVRAsync();
  12641. return this.onVRDisplayChangedObservable;
  12642. };
  12643. /**
  12644. * Initializes a webVR display and starts listening to display change events
  12645. * The onVRDisplayChangedObservable will be notified upon these changes
  12646. * @returns A promise containing a VRDisplay and if vr is supported
  12647. */
  12648. Engine.prototype.initWebVRAsync = function () {
  12649. var _this = this;
  12650. var notifyObservers = function () {
  12651. var eventArgs = {
  12652. vrDisplay: _this._vrDisplay,
  12653. vrSupported: _this._vrSupported
  12654. };
  12655. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12656. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12657. };
  12658. if (!this._onVrDisplayConnect) {
  12659. this._onVrDisplayConnect = function (event) {
  12660. _this._vrDisplay = event.display;
  12661. notifyObservers();
  12662. };
  12663. this._onVrDisplayDisconnect = function () {
  12664. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12665. _this._vrDisplay = undefined;
  12666. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12667. notifyObservers();
  12668. };
  12669. this._onVrDisplayPresentChange = function () {
  12670. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12671. };
  12672. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12673. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12674. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12675. }
  12676. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12677. this._webVRInitPromise.then(notifyObservers);
  12678. return this._webVRInitPromise;
  12679. };
  12680. /**
  12681. * Call this function to switch to webVR mode
  12682. * Will do nothing if webVR is not supported or if there is no webVR device
  12683. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12684. */
  12685. Engine.prototype.enableVR = function () {
  12686. var _this = this;
  12687. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12688. var onResolved = function () {
  12689. _this.onVRRequestPresentComplete.notifyObservers(true);
  12690. _this._onVRFullScreenTriggered();
  12691. };
  12692. var onRejected = function () {
  12693. _this.onVRRequestPresentComplete.notifyObservers(false);
  12694. };
  12695. this.onVRRequestPresentStart.notifyObservers(this);
  12696. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12697. }
  12698. };
  12699. /**
  12700. * Call this function to leave webVR mode
  12701. * Will do nothing if webVR is not supported or if there is no webVR device
  12702. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12703. */
  12704. Engine.prototype.disableVR = function () {
  12705. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12706. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12707. }
  12708. };
  12709. Engine.prototype._getVRDisplaysAsync = function () {
  12710. var _this = this;
  12711. return new Promise(function (res, rej) {
  12712. if (navigator.getVRDisplays) {
  12713. navigator.getVRDisplays().then(function (devices) {
  12714. _this._vrSupported = true;
  12715. // note that devices may actually be an empty array. This is fine;
  12716. // we expect this._vrDisplay to be undefined in this case.
  12717. _this._vrDisplay = devices[0];
  12718. res({
  12719. vrDisplay: _this._vrDisplay,
  12720. vrSupported: _this._vrSupported
  12721. });
  12722. });
  12723. }
  12724. else {
  12725. _this._vrDisplay = undefined;
  12726. _this._vrSupported = false;
  12727. res({
  12728. vrDisplay: _this._vrDisplay,
  12729. vrSupported: _this._vrSupported
  12730. });
  12731. }
  12732. });
  12733. };
  12734. /**
  12735. * Binds the frame buffer to the specified texture.
  12736. * @param texture The texture to render to or null for the default canvas
  12737. * @param faceIndex The face of the texture to render to in case of cube texture
  12738. * @param requiredWidth The width of the target to render to
  12739. * @param requiredHeight The height of the target to render to
  12740. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12741. * @param depthStencilTexture The depth stencil texture to use to render
  12742. * @param lodLevel defines le lod level to bind to the frame buffer
  12743. */
  12744. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12745. if (lodLevel === void 0) { lodLevel = 0; }
  12746. if (this._currentRenderTarget) {
  12747. this.unBindFramebuffer(this._currentRenderTarget);
  12748. }
  12749. this._currentRenderTarget = texture;
  12750. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12751. var gl = this._gl;
  12752. if (texture.isCube) {
  12753. if (faceIndex === undefined) {
  12754. faceIndex = 0;
  12755. }
  12756. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12757. if (depthStencilTexture) {
  12758. if (depthStencilTexture._generateStencilBuffer) {
  12759. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12760. }
  12761. else {
  12762. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12763. }
  12764. }
  12765. }
  12766. if (this._cachedViewport && !forceFullscreenViewport) {
  12767. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12768. }
  12769. else {
  12770. if (!requiredWidth) {
  12771. requiredWidth = texture.width;
  12772. if (lodLevel) {
  12773. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12774. }
  12775. }
  12776. if (!requiredHeight) {
  12777. requiredHeight = texture.height;
  12778. if (lodLevel) {
  12779. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12780. }
  12781. }
  12782. this._viewport(0, 0, requiredWidth, requiredHeight);
  12783. }
  12784. this.wipeCaches();
  12785. };
  12786. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12787. if (this._currentFramebuffer !== framebuffer) {
  12788. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12789. this._currentFramebuffer = framebuffer;
  12790. }
  12791. };
  12792. /**
  12793. * Unbind the current render target texture from the webGL context
  12794. * @param texture defines the render target texture to unbind
  12795. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12796. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12797. */
  12798. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12799. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12800. this._currentRenderTarget = null;
  12801. // If MSAA, we need to bitblt back to main texture
  12802. var gl = this._gl;
  12803. if (texture._MSAAFramebuffer) {
  12804. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12805. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12806. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12807. }
  12808. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12809. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12810. gl.generateMipmap(gl.TEXTURE_2D);
  12811. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12812. }
  12813. if (onBeforeUnbind) {
  12814. if (texture._MSAAFramebuffer) {
  12815. // Bind the correct framebuffer
  12816. this.bindUnboundFramebuffer(texture._framebuffer);
  12817. }
  12818. onBeforeUnbind();
  12819. }
  12820. this.bindUnboundFramebuffer(null);
  12821. };
  12822. /**
  12823. * Unbind a list of render target textures from the webGL context
  12824. * This is used only when drawBuffer extension or webGL2 are active
  12825. * @param textures defines the render target textures to unbind
  12826. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12827. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12828. */
  12829. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12830. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12831. this._currentRenderTarget = null;
  12832. // If MSAA, we need to bitblt back to main texture
  12833. var gl = this._gl;
  12834. if (textures[0]._MSAAFramebuffer) {
  12835. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12836. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12837. var attachments = textures[0]._attachments;
  12838. if (!attachments) {
  12839. attachments = new Array(textures.length);
  12840. textures[0]._attachments = attachments;
  12841. }
  12842. for (var i = 0; i < textures.length; i++) {
  12843. var texture = textures[i];
  12844. for (var j = 0; j < attachments.length; j++) {
  12845. attachments[j] = gl.NONE;
  12846. }
  12847. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12848. gl.readBuffer(attachments[i]);
  12849. gl.drawBuffers(attachments);
  12850. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12851. }
  12852. for (var i = 0; i < attachments.length; i++) {
  12853. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12854. }
  12855. gl.drawBuffers(attachments);
  12856. }
  12857. for (var i = 0; i < textures.length; i++) {
  12858. var texture = textures[i];
  12859. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12860. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12861. gl.generateMipmap(gl.TEXTURE_2D);
  12862. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12863. }
  12864. }
  12865. if (onBeforeUnbind) {
  12866. if (textures[0]._MSAAFramebuffer) {
  12867. // Bind the correct framebuffer
  12868. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12869. }
  12870. onBeforeUnbind();
  12871. }
  12872. this.bindUnboundFramebuffer(null);
  12873. };
  12874. /**
  12875. * Force the mipmap generation for the given render target texture
  12876. * @param texture defines the render target texture to use
  12877. */
  12878. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12879. if (texture.generateMipMaps) {
  12880. var gl = this._gl;
  12881. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12882. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12883. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12884. }
  12885. };
  12886. /**
  12887. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12888. */
  12889. Engine.prototype.flushFramebuffer = function () {
  12890. this._gl.flush();
  12891. };
  12892. /**
  12893. * Unbind the current render target and bind the default framebuffer
  12894. */
  12895. Engine.prototype.restoreDefaultFramebuffer = function () {
  12896. if (this._currentRenderTarget) {
  12897. this.unBindFramebuffer(this._currentRenderTarget);
  12898. }
  12899. else {
  12900. this.bindUnboundFramebuffer(null);
  12901. }
  12902. if (this._cachedViewport) {
  12903. this.setViewport(this._cachedViewport);
  12904. }
  12905. this.wipeCaches();
  12906. };
  12907. // UBOs
  12908. /**
  12909. * Create an uniform buffer
  12910. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12911. * @param elements defines the content of the uniform buffer
  12912. * @returns the webGL uniform buffer
  12913. */
  12914. Engine.prototype.createUniformBuffer = function (elements) {
  12915. var ubo = this._gl.createBuffer();
  12916. if (!ubo) {
  12917. throw new Error("Unable to create uniform buffer");
  12918. }
  12919. this.bindUniformBuffer(ubo);
  12920. if (elements instanceof Float32Array) {
  12921. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12922. }
  12923. else {
  12924. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12925. }
  12926. this.bindUniformBuffer(null);
  12927. ubo.references = 1;
  12928. return ubo;
  12929. };
  12930. /**
  12931. * Create a dynamic uniform buffer
  12932. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12933. * @param elements defines the content of the uniform buffer
  12934. * @returns the webGL uniform buffer
  12935. */
  12936. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12937. var ubo = this._gl.createBuffer();
  12938. if (!ubo) {
  12939. throw new Error("Unable to create dynamic uniform buffer");
  12940. }
  12941. this.bindUniformBuffer(ubo);
  12942. if (elements instanceof Float32Array) {
  12943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12944. }
  12945. else {
  12946. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12947. }
  12948. this.bindUniformBuffer(null);
  12949. ubo.references = 1;
  12950. return ubo;
  12951. };
  12952. /**
  12953. * Update an existing uniform buffer
  12954. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12955. * @param uniformBuffer defines the target uniform buffer
  12956. * @param elements defines the content to update
  12957. * @param offset defines the offset in the uniform buffer where update should start
  12958. * @param count defines the size of the data to update
  12959. */
  12960. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12961. this.bindUniformBuffer(uniformBuffer);
  12962. if (offset === undefined) {
  12963. offset = 0;
  12964. }
  12965. if (count === undefined) {
  12966. if (elements instanceof Float32Array) {
  12967. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12968. }
  12969. else {
  12970. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12971. }
  12972. }
  12973. else {
  12974. if (elements instanceof Float32Array) {
  12975. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12976. }
  12977. else {
  12978. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12979. }
  12980. }
  12981. this.bindUniformBuffer(null);
  12982. };
  12983. // VBOs
  12984. Engine.prototype._resetVertexBufferBinding = function () {
  12985. this.bindArrayBuffer(null);
  12986. this._cachedVertexBuffers = null;
  12987. };
  12988. /**
  12989. * Creates a vertex buffer
  12990. * @param data the data for the vertex buffer
  12991. * @returns the new WebGL static buffer
  12992. */
  12993. Engine.prototype.createVertexBuffer = function (data) {
  12994. var vbo = this._gl.createBuffer();
  12995. if (!vbo) {
  12996. throw new Error("Unable to create vertex buffer");
  12997. }
  12998. this.bindArrayBuffer(vbo);
  12999. if (data instanceof Array) {
  13000. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13001. }
  13002. else {
  13003. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13004. }
  13005. this._resetVertexBufferBinding();
  13006. vbo.references = 1;
  13007. return vbo;
  13008. };
  13009. /**
  13010. * Creates a dynamic vertex buffer
  13011. * @param data the data for the dynamic vertex buffer
  13012. * @returns the new WebGL dynamic buffer
  13013. */
  13014. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13015. var vbo = this._gl.createBuffer();
  13016. if (!vbo) {
  13017. throw new Error("Unable to create dynamic vertex buffer");
  13018. }
  13019. this.bindArrayBuffer(vbo);
  13020. if (data instanceof Array) {
  13021. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13022. }
  13023. else {
  13024. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13025. }
  13026. this._resetVertexBufferBinding();
  13027. vbo.references = 1;
  13028. return vbo;
  13029. };
  13030. /**
  13031. * Update a dynamic index buffer
  13032. * @param indexBuffer defines the target index buffer
  13033. * @param indices defines the data to update
  13034. * @param offset defines the offset in the target index buffer where update should start
  13035. */
  13036. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13037. if (offset === void 0) { offset = 0; }
  13038. // Force cache update
  13039. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13040. this.bindIndexBuffer(indexBuffer);
  13041. var arrayBuffer;
  13042. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13043. arrayBuffer = indices;
  13044. }
  13045. else {
  13046. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13047. }
  13048. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13049. this._resetIndexBufferBinding();
  13050. };
  13051. /**
  13052. * Updates a dynamic vertex buffer.
  13053. * @param vertexBuffer the vertex buffer to update
  13054. * @param data the data used to update the vertex buffer
  13055. * @param byteOffset the byte offset of the data
  13056. * @param byteLength the byte length of the data
  13057. */
  13058. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13059. this.bindArrayBuffer(vertexBuffer);
  13060. if (byteOffset === undefined) {
  13061. byteOffset = 0;
  13062. }
  13063. if (byteLength === undefined) {
  13064. if (data instanceof Array) {
  13065. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13066. }
  13067. else {
  13068. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13069. }
  13070. }
  13071. else {
  13072. if (data instanceof Array) {
  13073. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13074. }
  13075. else {
  13076. if (data instanceof ArrayBuffer) {
  13077. data = new Uint8Array(data, byteOffset, byteLength);
  13078. }
  13079. else {
  13080. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13081. }
  13082. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13083. }
  13084. }
  13085. this._resetVertexBufferBinding();
  13086. };
  13087. Engine.prototype._resetIndexBufferBinding = function () {
  13088. this.bindIndexBuffer(null);
  13089. this._cachedIndexBuffer = null;
  13090. };
  13091. /**
  13092. * Creates a new index buffer
  13093. * @param indices defines the content of the index buffer
  13094. * @param updatable defines if the index buffer must be updatable
  13095. * @returns a new webGL buffer
  13096. */
  13097. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13098. var vbo = this._gl.createBuffer();
  13099. if (!vbo) {
  13100. throw new Error("Unable to create index buffer");
  13101. }
  13102. this.bindIndexBuffer(vbo);
  13103. // Check for 32 bits indices
  13104. var arrayBuffer;
  13105. var need32Bits = false;
  13106. if (indices instanceof Uint16Array) {
  13107. arrayBuffer = indices;
  13108. }
  13109. else {
  13110. //check 32 bit support
  13111. if (this._caps.uintIndices) {
  13112. if (indices instanceof Uint32Array) {
  13113. arrayBuffer = indices;
  13114. need32Bits = true;
  13115. }
  13116. else {
  13117. //number[] or Int32Array, check if 32 bit is necessary
  13118. for (var index = 0; index < indices.length; index++) {
  13119. if (indices[index] > 65535) {
  13120. need32Bits = true;
  13121. break;
  13122. }
  13123. }
  13124. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13125. }
  13126. }
  13127. else {
  13128. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13129. arrayBuffer = new Uint16Array(indices);
  13130. }
  13131. }
  13132. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13133. this._resetIndexBufferBinding();
  13134. vbo.references = 1;
  13135. vbo.is32Bits = need32Bits;
  13136. return vbo;
  13137. };
  13138. /**
  13139. * Bind a webGL buffer to the webGL context
  13140. * @param buffer defines the buffer to bind
  13141. */
  13142. Engine.prototype.bindArrayBuffer = function (buffer) {
  13143. if (!this._vaoRecordInProgress) {
  13144. this._unbindVertexArrayObject();
  13145. }
  13146. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13147. };
  13148. /**
  13149. * Bind an uniform buffer to the current webGL context
  13150. * @param buffer defines the buffer to bind
  13151. */
  13152. Engine.prototype.bindUniformBuffer = function (buffer) {
  13153. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13154. };
  13155. /**
  13156. * Bind a buffer to the current webGL context at a given location
  13157. * @param buffer defines the buffer to bind
  13158. * @param location defines the index where to bind the buffer
  13159. */
  13160. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13161. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13162. };
  13163. /**
  13164. * Bind a specific block at a given index in a specific shader program
  13165. * @param shaderProgram defines the shader program
  13166. * @param blockName defines the block name
  13167. * @param index defines the index where to bind the block
  13168. */
  13169. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13170. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13171. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13172. };
  13173. ;
  13174. Engine.prototype.bindIndexBuffer = function (buffer) {
  13175. if (!this._vaoRecordInProgress) {
  13176. this._unbindVertexArrayObject();
  13177. }
  13178. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13179. };
  13180. Engine.prototype.bindBuffer = function (buffer, target) {
  13181. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13182. this._gl.bindBuffer(target, buffer);
  13183. this._currentBoundBuffer[target] = buffer;
  13184. }
  13185. };
  13186. /**
  13187. * update the bound buffer with the given data
  13188. * @param data defines the data to update
  13189. */
  13190. Engine.prototype.updateArrayBuffer = function (data) {
  13191. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13192. };
  13193. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13194. var pointer = this._currentBufferPointers[indx];
  13195. var changed = false;
  13196. if (!pointer.active) {
  13197. changed = true;
  13198. pointer.active = true;
  13199. pointer.index = indx;
  13200. pointer.size = size;
  13201. pointer.type = type;
  13202. pointer.normalized = normalized;
  13203. pointer.stride = stride;
  13204. pointer.offset = offset;
  13205. pointer.buffer = buffer;
  13206. }
  13207. else {
  13208. if (pointer.buffer !== buffer) {
  13209. pointer.buffer = buffer;
  13210. changed = true;
  13211. }
  13212. if (pointer.size !== size) {
  13213. pointer.size = size;
  13214. changed = true;
  13215. }
  13216. if (pointer.type !== type) {
  13217. pointer.type = type;
  13218. changed = true;
  13219. }
  13220. if (pointer.normalized !== normalized) {
  13221. pointer.normalized = normalized;
  13222. changed = true;
  13223. }
  13224. if (pointer.stride !== stride) {
  13225. pointer.stride = stride;
  13226. changed = true;
  13227. }
  13228. if (pointer.offset !== offset) {
  13229. pointer.offset = offset;
  13230. changed = true;
  13231. }
  13232. }
  13233. if (changed || this._vaoRecordInProgress) {
  13234. this.bindArrayBuffer(buffer);
  13235. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13236. }
  13237. };
  13238. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13239. if (indexBuffer == null) {
  13240. return;
  13241. }
  13242. if (this._cachedIndexBuffer !== indexBuffer) {
  13243. this._cachedIndexBuffer = indexBuffer;
  13244. this.bindIndexBuffer(indexBuffer);
  13245. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13246. }
  13247. };
  13248. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13249. var attributes = effect.getAttributesNames();
  13250. if (!this._vaoRecordInProgress) {
  13251. this._unbindVertexArrayObject();
  13252. }
  13253. this.unbindAllAttributes();
  13254. for (var index = 0; index < attributes.length; index++) {
  13255. var order = effect.getAttributeLocation(index);
  13256. if (order >= 0) {
  13257. var vertexBuffer = vertexBuffers[attributes[index]];
  13258. if (!vertexBuffer) {
  13259. continue;
  13260. }
  13261. this._gl.enableVertexAttribArray(order);
  13262. if (!this._vaoRecordInProgress) {
  13263. this._vertexAttribArraysEnabled[order] = true;
  13264. }
  13265. var buffer = vertexBuffer.getBuffer();
  13266. if (buffer) {
  13267. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13268. if (vertexBuffer.getIsInstanced()) {
  13269. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13270. if (!this._vaoRecordInProgress) {
  13271. this._currentInstanceLocations.push(order);
  13272. this._currentInstanceBuffers.push(buffer);
  13273. }
  13274. }
  13275. }
  13276. }
  13277. }
  13278. };
  13279. /**
  13280. * Records a vertex array object
  13281. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13282. * @param vertexBuffers defines the list of vertex buffers to store
  13283. * @param indexBuffer defines the index buffer to store
  13284. * @param effect defines the effect to store
  13285. * @returns the new vertex array object
  13286. */
  13287. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13288. var vao = this._gl.createVertexArray();
  13289. this._vaoRecordInProgress = true;
  13290. this._gl.bindVertexArray(vao);
  13291. this._mustWipeVertexAttributes = true;
  13292. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13293. this.bindIndexBuffer(indexBuffer);
  13294. this._vaoRecordInProgress = false;
  13295. this._gl.bindVertexArray(null);
  13296. return vao;
  13297. };
  13298. /**
  13299. * Bind a specific vertex array object
  13300. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13301. * @param vertexArrayObject defines the vertex array object to bind
  13302. * @param indexBuffer defines the index buffer to bind
  13303. */
  13304. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13305. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13306. this._cachedVertexArrayObject = vertexArrayObject;
  13307. this._gl.bindVertexArray(vertexArrayObject);
  13308. this._cachedVertexBuffers = null;
  13309. this._cachedIndexBuffer = null;
  13310. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13311. this._mustWipeVertexAttributes = true;
  13312. }
  13313. };
  13314. /**
  13315. * Bind webGl buffers directly to the webGL context
  13316. * @param vertexBuffer defines the vertex buffer to bind
  13317. * @param indexBuffer defines the index buffer to bind
  13318. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13319. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13320. * @param effect defines the effect associated with the vertex buffer
  13321. */
  13322. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13323. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13324. this._cachedVertexBuffers = vertexBuffer;
  13325. this._cachedEffectForVertexBuffers = effect;
  13326. var attributesCount = effect.getAttributesCount();
  13327. this._unbindVertexArrayObject();
  13328. this.unbindAllAttributes();
  13329. var offset = 0;
  13330. for (var index = 0; index < attributesCount; index++) {
  13331. if (index < vertexDeclaration.length) {
  13332. var order = effect.getAttributeLocation(index);
  13333. if (order >= 0) {
  13334. this._gl.enableVertexAttribArray(order);
  13335. this._vertexAttribArraysEnabled[order] = true;
  13336. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13337. }
  13338. offset += vertexDeclaration[index] * 4;
  13339. }
  13340. }
  13341. }
  13342. this._bindIndexBufferWithCache(indexBuffer);
  13343. };
  13344. Engine.prototype._unbindVertexArrayObject = function () {
  13345. if (!this._cachedVertexArrayObject) {
  13346. return;
  13347. }
  13348. this._cachedVertexArrayObject = null;
  13349. this._gl.bindVertexArray(null);
  13350. };
  13351. /**
  13352. * Bind a list of vertex buffers to the webGL context
  13353. * @param vertexBuffers defines the list of vertex buffers to bind
  13354. * @param indexBuffer defines the index buffer to bind
  13355. * @param effect defines the effect associated with the vertex buffers
  13356. */
  13357. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13358. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13359. this._cachedVertexBuffers = vertexBuffers;
  13360. this._cachedEffectForVertexBuffers = effect;
  13361. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13362. }
  13363. this._bindIndexBufferWithCache(indexBuffer);
  13364. };
  13365. /**
  13366. * Unbind all instance attributes
  13367. */
  13368. Engine.prototype.unbindInstanceAttributes = function () {
  13369. var boundBuffer;
  13370. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13371. var instancesBuffer = this._currentInstanceBuffers[i];
  13372. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13373. boundBuffer = instancesBuffer;
  13374. this.bindArrayBuffer(instancesBuffer);
  13375. }
  13376. var offsetLocation = this._currentInstanceLocations[i];
  13377. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13378. }
  13379. this._currentInstanceBuffers.length = 0;
  13380. this._currentInstanceLocations.length = 0;
  13381. };
  13382. /**
  13383. * Release and free the memory of a vertex array object
  13384. * @param vao defines the vertex array object to delete
  13385. */
  13386. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13387. this._gl.deleteVertexArray(vao);
  13388. };
  13389. /** @hidden */
  13390. Engine.prototype._releaseBuffer = function (buffer) {
  13391. buffer.references--;
  13392. if (buffer.references === 0) {
  13393. this._gl.deleteBuffer(buffer);
  13394. return true;
  13395. }
  13396. return false;
  13397. };
  13398. /**
  13399. * Creates a webGL buffer to use with instanciation
  13400. * @param capacity defines the size of the buffer
  13401. * @returns the webGL buffer
  13402. */
  13403. Engine.prototype.createInstancesBuffer = function (capacity) {
  13404. var buffer = this._gl.createBuffer();
  13405. if (!buffer) {
  13406. throw new Error("Unable to create instance buffer");
  13407. }
  13408. buffer.capacity = capacity;
  13409. this.bindArrayBuffer(buffer);
  13410. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13411. return buffer;
  13412. };
  13413. /**
  13414. * Delete a webGL buffer used with instanciation
  13415. * @param buffer defines the webGL buffer to delete
  13416. */
  13417. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13418. this._gl.deleteBuffer(buffer);
  13419. };
  13420. /**
  13421. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13422. * @param instancesBuffer defines the webGL buffer to update and bind
  13423. * @param data defines the data to store in the buffer
  13424. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13425. */
  13426. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13427. this.bindArrayBuffer(instancesBuffer);
  13428. if (data) {
  13429. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13430. }
  13431. if (offsetLocations[0].index !== undefined) {
  13432. var stride = 0;
  13433. for (var i = 0; i < offsetLocations.length; i++) {
  13434. var ai = offsetLocations[i];
  13435. stride += ai.attributeSize * 4;
  13436. }
  13437. for (var i = 0; i < offsetLocations.length; i++) {
  13438. var ai = offsetLocations[i];
  13439. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13440. this._gl.enableVertexAttribArray(ai.index);
  13441. this._vertexAttribArraysEnabled[ai.index] = true;
  13442. }
  13443. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13444. this._gl.vertexAttribDivisor(ai.index, 1);
  13445. this._currentInstanceLocations.push(ai.index);
  13446. this._currentInstanceBuffers.push(instancesBuffer);
  13447. }
  13448. }
  13449. else {
  13450. for (var index = 0; index < 4; index++) {
  13451. var offsetLocation = offsetLocations[index];
  13452. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13453. this._gl.enableVertexAttribArray(offsetLocation);
  13454. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13455. }
  13456. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13457. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13458. this._currentInstanceLocations.push(offsetLocation);
  13459. this._currentInstanceBuffers.push(instancesBuffer);
  13460. }
  13461. }
  13462. };
  13463. /**
  13464. * Apply all cached states (depth, culling, stencil and alpha)
  13465. */
  13466. Engine.prototype.applyStates = function () {
  13467. this._depthCullingState.apply(this._gl);
  13468. this._stencilState.apply(this._gl);
  13469. this._alphaState.apply(this._gl);
  13470. };
  13471. /**
  13472. * Send a draw order
  13473. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13474. * @param indexStart defines the starting index
  13475. * @param indexCount defines the number of index to draw
  13476. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13477. */
  13478. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13479. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13480. };
  13481. /**
  13482. * Draw a list of points
  13483. * @param verticesStart defines the index of first vertex to draw
  13484. * @param verticesCount defines the count of vertices to draw
  13485. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13486. */
  13487. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13488. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13489. };
  13490. /**
  13491. * Draw a list of unindexed primitives
  13492. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13493. * @param verticesStart defines the index of first vertex to draw
  13494. * @param verticesCount defines the count of vertices to draw
  13495. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13496. */
  13497. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13498. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13499. };
  13500. /**
  13501. * Draw a list of indexed primitives
  13502. * @param fillMode defines the primitive to use
  13503. * @param indexStart defines the starting index
  13504. * @param indexCount defines the number of index to draw
  13505. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13506. */
  13507. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13508. // Apply states
  13509. this.applyStates();
  13510. this._drawCalls.addCount(1, false);
  13511. // Render
  13512. var drawMode = this._drawMode(fillMode);
  13513. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13514. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13515. if (instancesCount) {
  13516. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13517. }
  13518. else {
  13519. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13520. }
  13521. };
  13522. /**
  13523. * Draw a list of unindexed primitives
  13524. * @param fillMode defines the primitive to use
  13525. * @param verticesStart defines the index of first vertex to draw
  13526. * @param verticesCount defines the count of vertices to draw
  13527. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13528. */
  13529. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13530. // Apply states
  13531. this.applyStates();
  13532. this._drawCalls.addCount(1, false);
  13533. var drawMode = this._drawMode(fillMode);
  13534. if (instancesCount) {
  13535. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13536. }
  13537. else {
  13538. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13539. }
  13540. };
  13541. Engine.prototype._drawMode = function (fillMode) {
  13542. switch (fillMode) {
  13543. // Triangle views
  13544. case BABYLON.Material.TriangleFillMode:
  13545. return this._gl.TRIANGLES;
  13546. case BABYLON.Material.PointFillMode:
  13547. return this._gl.POINTS;
  13548. case BABYLON.Material.WireFrameFillMode:
  13549. return this._gl.LINES;
  13550. // Draw modes
  13551. case BABYLON.Material.PointListDrawMode:
  13552. return this._gl.POINTS;
  13553. case BABYLON.Material.LineListDrawMode:
  13554. return this._gl.LINES;
  13555. case BABYLON.Material.LineLoopDrawMode:
  13556. return this._gl.LINE_LOOP;
  13557. case BABYLON.Material.LineStripDrawMode:
  13558. return this._gl.LINE_STRIP;
  13559. case BABYLON.Material.TriangleStripDrawMode:
  13560. return this._gl.TRIANGLE_STRIP;
  13561. case BABYLON.Material.TriangleFanDrawMode:
  13562. return this._gl.TRIANGLE_FAN;
  13563. default:
  13564. return this._gl.TRIANGLES;
  13565. }
  13566. };
  13567. // Shaders
  13568. /** @hidden */
  13569. Engine.prototype._releaseEffect = function (effect) {
  13570. if (this._compiledEffects[effect._key]) {
  13571. delete this._compiledEffects[effect._key];
  13572. this._deleteProgram(effect.getProgram());
  13573. }
  13574. };
  13575. /** @hidden */
  13576. Engine.prototype._deleteProgram = function (program) {
  13577. if (program) {
  13578. program.__SPECTOR_rebuildProgram = null;
  13579. if (program.transformFeedback) {
  13580. this.deleteTransformFeedback(program.transformFeedback);
  13581. program.transformFeedback = null;
  13582. }
  13583. this._gl.deleteProgram(program);
  13584. }
  13585. };
  13586. /**
  13587. * Create a new effect (used to store vertex/fragment shaders)
  13588. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13589. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13590. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13591. * @param samplers defines an array of string used to represent textures
  13592. * @param defines defines the string containing the defines to use to compile the shaders
  13593. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13594. * @param onCompiled defines a function to call when the effect creation is successful
  13595. * @param onError defines a function to call when the effect creation has failed
  13596. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13597. * @returns the new Effect
  13598. */
  13599. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13600. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13601. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13602. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13603. if (this._compiledEffects[name]) {
  13604. var compiledEffect = this._compiledEffects[name];
  13605. if (onCompiled && compiledEffect.isReady()) {
  13606. onCompiled(compiledEffect);
  13607. }
  13608. return compiledEffect;
  13609. }
  13610. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13611. effect._key = name;
  13612. this._compiledEffects[name] = effect;
  13613. return effect;
  13614. };
  13615. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13616. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13617. };
  13618. ;
  13619. Engine.prototype._compileRawShader = function (source, type) {
  13620. var gl = this._gl;
  13621. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13622. gl.shaderSource(shader, source);
  13623. gl.compileShader(shader);
  13624. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13625. var log = gl.getShaderInfoLog(shader);
  13626. if (log) {
  13627. throw new Error(log);
  13628. }
  13629. }
  13630. if (!shader) {
  13631. throw new Error("Something went wrong while compile the shader.");
  13632. }
  13633. return shader;
  13634. };
  13635. ;
  13636. /**
  13637. * Directly creates a webGL program
  13638. * @param vertexCode defines the vertex shader code to use
  13639. * @param fragmentCode defines the fragment shader code to use
  13640. * @param context defines the webGL context to use (if not set, the current one will be used)
  13641. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13642. * @returns the new webGL program
  13643. */
  13644. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13645. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13646. context = context || this._gl;
  13647. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13648. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13649. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13650. };
  13651. /**
  13652. * Creates a webGL program
  13653. * @param vertexCode defines the vertex shader code to use
  13654. * @param fragmentCode defines the fragment shader code to use
  13655. * @param defines defines the string containing the defines to use to compile the shaders
  13656. * @param context defines the webGL context to use (if not set, the current one will be used)
  13657. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13658. * @returns the new webGL program
  13659. */
  13660. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13661. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13662. context = context || this._gl;
  13663. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13664. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13665. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13666. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13667. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13668. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13669. return program;
  13670. };
  13671. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13672. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13673. var shaderProgram = context.createProgram();
  13674. if (!shaderProgram) {
  13675. throw new Error("Unable to create program");
  13676. }
  13677. context.attachShader(shaderProgram, vertexShader);
  13678. context.attachShader(shaderProgram, fragmentShader);
  13679. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13680. var transformFeedback = this.createTransformFeedback();
  13681. this.bindTransformFeedback(transformFeedback);
  13682. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13683. shaderProgram.transformFeedback = transformFeedback;
  13684. }
  13685. context.linkProgram(shaderProgram);
  13686. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13687. this.bindTransformFeedback(null);
  13688. }
  13689. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13690. if (!linked) {
  13691. var error = context.getProgramInfoLog(shaderProgram);
  13692. if (error) {
  13693. throw new Error(error);
  13694. }
  13695. }
  13696. if (this.validateShaderPrograms) {
  13697. context.validateProgram(shaderProgram);
  13698. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13699. if (!validated) {
  13700. var error = context.getProgramInfoLog(shaderProgram);
  13701. if (error) {
  13702. throw new Error(error);
  13703. }
  13704. }
  13705. }
  13706. context.deleteShader(vertexShader);
  13707. context.deleteShader(fragmentShader);
  13708. return shaderProgram;
  13709. };
  13710. /**
  13711. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13712. * @param shaderProgram defines the webGL program to use
  13713. * @param uniformsNames defines the list of uniform names
  13714. * @returns an array of webGL uniform locations
  13715. */
  13716. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13717. var results = new Array();
  13718. for (var index = 0; index < uniformsNames.length; index++) {
  13719. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13720. }
  13721. return results;
  13722. };
  13723. /**
  13724. * Gets the lsit of active attributes for a given webGL program
  13725. * @param shaderProgram defines the webGL program to use
  13726. * @param attributesNames defines the list of attribute names to get
  13727. * @returns an array of indices indicating the offset of each attribute
  13728. */
  13729. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13730. var results = [];
  13731. for (var index = 0; index < attributesNames.length; index++) {
  13732. try {
  13733. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13734. }
  13735. catch (e) {
  13736. results.push(-1);
  13737. }
  13738. }
  13739. return results;
  13740. };
  13741. /**
  13742. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13743. * @param effect defines the effect to activate
  13744. */
  13745. Engine.prototype.enableEffect = function (effect) {
  13746. if (!effect || effect === this._currentEffect) {
  13747. return;
  13748. }
  13749. // Use program
  13750. this.bindSamplers(effect);
  13751. this._currentEffect = effect;
  13752. if (effect.onBind) {
  13753. effect.onBind(effect);
  13754. }
  13755. if (effect._onBindObservable) {
  13756. effect._onBindObservable.notifyObservers(effect);
  13757. }
  13758. };
  13759. /**
  13760. * Set the value of an uniform to an array of int32
  13761. * @param uniform defines the webGL uniform location where to store the value
  13762. * @param array defines the array of int32 to store
  13763. */
  13764. Engine.prototype.setIntArray = function (uniform, array) {
  13765. if (!uniform)
  13766. return;
  13767. this._gl.uniform1iv(uniform, array);
  13768. };
  13769. /**
  13770. * Set the value of an uniform to an array of int32 (stored as vec2)
  13771. * @param uniform defines the webGL uniform location where to store the value
  13772. * @param array defines the array of int32 to store
  13773. */
  13774. Engine.prototype.setIntArray2 = function (uniform, array) {
  13775. if (!uniform || array.length % 2 !== 0)
  13776. return;
  13777. this._gl.uniform2iv(uniform, array);
  13778. };
  13779. /**
  13780. * Set the value of an uniform to an array of int32 (stored as vec3)
  13781. * @param uniform defines the webGL uniform location where to store the value
  13782. * @param array defines the array of int32 to store
  13783. */
  13784. Engine.prototype.setIntArray3 = function (uniform, array) {
  13785. if (!uniform || array.length % 3 !== 0)
  13786. return;
  13787. this._gl.uniform3iv(uniform, array);
  13788. };
  13789. /**
  13790. * Set the value of an uniform to an array of int32 (stored as vec4)
  13791. * @param uniform defines the webGL uniform location where to store the value
  13792. * @param array defines the array of int32 to store
  13793. */
  13794. Engine.prototype.setIntArray4 = function (uniform, array) {
  13795. if (!uniform || array.length % 4 !== 0)
  13796. return;
  13797. this._gl.uniform4iv(uniform, array);
  13798. };
  13799. /**
  13800. * Set the value of an uniform to an array of float32
  13801. * @param uniform defines the webGL uniform location where to store the value
  13802. * @param array defines the array of float32 to store
  13803. */
  13804. Engine.prototype.setFloatArray = function (uniform, array) {
  13805. if (!uniform)
  13806. return;
  13807. this._gl.uniform1fv(uniform, array);
  13808. };
  13809. /**
  13810. * Set the value of an uniform to an array of float32 (stored as vec2)
  13811. * @param uniform defines the webGL uniform location where to store the value
  13812. * @param array defines the array of float32 to store
  13813. */
  13814. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13815. if (!uniform || array.length % 2 !== 0)
  13816. return;
  13817. this._gl.uniform2fv(uniform, array);
  13818. };
  13819. /**
  13820. * Set the value of an uniform to an array of float32 (stored as vec3)
  13821. * @param uniform defines the webGL uniform location where to store the value
  13822. * @param array defines the array of float32 to store
  13823. */
  13824. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13825. if (!uniform || array.length % 3 !== 0)
  13826. return;
  13827. this._gl.uniform3fv(uniform, array);
  13828. };
  13829. /**
  13830. * Set the value of an uniform to an array of float32 (stored as vec4)
  13831. * @param uniform defines the webGL uniform location where to store the value
  13832. * @param array defines the array of float32 to store
  13833. */
  13834. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13835. if (!uniform || array.length % 4 !== 0)
  13836. return;
  13837. this._gl.uniform4fv(uniform, array);
  13838. };
  13839. /**
  13840. * Set the value of an uniform to an array of number
  13841. * @param uniform defines the webGL uniform location where to store the value
  13842. * @param array defines the array of number to store
  13843. */
  13844. Engine.prototype.setArray = function (uniform, array) {
  13845. if (!uniform)
  13846. return;
  13847. this._gl.uniform1fv(uniform, array);
  13848. };
  13849. /**
  13850. * Set the value of an uniform to an array of number (stored as vec2)
  13851. * @param uniform defines the webGL uniform location where to store the value
  13852. * @param array defines the array of number to store
  13853. */
  13854. Engine.prototype.setArray2 = function (uniform, array) {
  13855. if (!uniform || array.length % 2 !== 0)
  13856. return;
  13857. this._gl.uniform2fv(uniform, array);
  13858. };
  13859. /**
  13860. * Set the value of an uniform to an array of number (stored as vec3)
  13861. * @param uniform defines the webGL uniform location where to store the value
  13862. * @param array defines the array of number to store
  13863. */
  13864. Engine.prototype.setArray3 = function (uniform, array) {
  13865. if (!uniform || array.length % 3 !== 0)
  13866. return;
  13867. this._gl.uniform3fv(uniform, array);
  13868. };
  13869. /**
  13870. * Set the value of an uniform to an array of number (stored as vec4)
  13871. * @param uniform defines the webGL uniform location where to store the value
  13872. * @param array defines the array of number to store
  13873. */
  13874. Engine.prototype.setArray4 = function (uniform, array) {
  13875. if (!uniform || array.length % 4 !== 0)
  13876. return;
  13877. this._gl.uniform4fv(uniform, array);
  13878. };
  13879. /**
  13880. * Set the value of an uniform to an array of float32 (stored as matrices)
  13881. * @param uniform defines the webGL uniform location where to store the value
  13882. * @param matrices defines the array of float32 to store
  13883. */
  13884. Engine.prototype.setMatrices = function (uniform, matrices) {
  13885. if (!uniform)
  13886. return;
  13887. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13888. };
  13889. /**
  13890. * Set the value of an uniform to a matrix
  13891. * @param uniform defines the webGL uniform location where to store the value
  13892. * @param matrix defines the matrix to store
  13893. */
  13894. Engine.prototype.setMatrix = function (uniform, matrix) {
  13895. if (!uniform)
  13896. return;
  13897. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13898. };
  13899. /**
  13900. * Set the value of an uniform to a matrix (3x3)
  13901. * @param uniform defines the webGL uniform location where to store the value
  13902. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13903. */
  13904. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13905. if (!uniform)
  13906. return;
  13907. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to a matrix (2x2)
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13913. */
  13914. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13915. if (!uniform)
  13916. return;
  13917. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13918. };
  13919. /**
  13920. * Set the value of an uniform to a number (int)
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param value defines the int number to store
  13923. */
  13924. Engine.prototype.setInt = function (uniform, value) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniform1i(uniform, value);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to a number (float)
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param value defines the float number to store
  13933. */
  13934. Engine.prototype.setFloat = function (uniform, value) {
  13935. if (!uniform)
  13936. return;
  13937. this._gl.uniform1f(uniform, value);
  13938. };
  13939. /**
  13940. * Set the value of an uniform to a vec2
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param x defines the 1st component of the value
  13943. * @param y defines the 2nd component of the value
  13944. */
  13945. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13946. if (!uniform)
  13947. return;
  13948. this._gl.uniform2f(uniform, x, y);
  13949. };
  13950. /**
  13951. * Set the value of an uniform to a vec3
  13952. * @param uniform defines the webGL uniform location where to store the value
  13953. * @param x defines the 1st component of the value
  13954. * @param y defines the 2nd component of the value
  13955. * @param z defines the 3rd component of the value
  13956. */
  13957. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13958. if (!uniform)
  13959. return;
  13960. this._gl.uniform3f(uniform, x, y, z);
  13961. };
  13962. /**
  13963. * Set the value of an uniform to a boolean
  13964. * @param uniform defines the webGL uniform location where to store the value
  13965. * @param bool defines the boolean to store
  13966. */
  13967. Engine.prototype.setBool = function (uniform, bool) {
  13968. if (!uniform)
  13969. return;
  13970. this._gl.uniform1i(uniform, bool);
  13971. };
  13972. /**
  13973. * Set the value of an uniform to a vec4
  13974. * @param uniform defines the webGL uniform location where to store the value
  13975. * @param x defines the 1st component of the value
  13976. * @param y defines the 2nd component of the value
  13977. * @param z defines the 3rd component of the value
  13978. * @param w defines the 4th component of the value
  13979. */
  13980. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13981. if (!uniform)
  13982. return;
  13983. this._gl.uniform4f(uniform, x, y, z, w);
  13984. };
  13985. /**
  13986. * Set the value of an uniform to a Color3
  13987. * @param uniform defines the webGL uniform location where to store the value
  13988. * @param color3 defines the color to store
  13989. */
  13990. Engine.prototype.setColor3 = function (uniform, color3) {
  13991. if (!uniform)
  13992. return;
  13993. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13994. };
  13995. /**
  13996. * Set the value of an uniform to a Color3 and an alpha value
  13997. * @param uniform defines the webGL uniform location where to store the value
  13998. * @param color3 defines the color to store
  13999. * @param alpha defines the alpha component to store
  14000. */
  14001. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14002. if (!uniform)
  14003. return;
  14004. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14005. };
  14006. /**
  14007. * Sets a Color4 on a uniform variable
  14008. * @param uniform defines the uniform location
  14009. * @param color4 defines the value to be set
  14010. */
  14011. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14012. if (!uniform)
  14013. return;
  14014. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14015. };
  14016. // States
  14017. /**
  14018. * Set various states to the webGL context
  14019. * @param culling defines backface culling state
  14020. * @param zOffset defines the value to apply to zOffset (0 by default)
  14021. * @param force defines if states must be applied even if cache is up to date
  14022. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14023. */
  14024. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14025. if (zOffset === void 0) { zOffset = 0; }
  14026. if (reverseSide === void 0) { reverseSide = false; }
  14027. // Culling
  14028. if (this._depthCullingState.cull !== culling || force) {
  14029. this._depthCullingState.cull = culling;
  14030. }
  14031. // Cull face
  14032. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14033. if (this._depthCullingState.cullFace !== cullFace || force) {
  14034. this._depthCullingState.cullFace = cullFace;
  14035. }
  14036. // Z offset
  14037. this.setZOffset(zOffset);
  14038. // Front face
  14039. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14040. if (this._depthCullingState.frontFace !== frontFace || force) {
  14041. this._depthCullingState.frontFace = frontFace;
  14042. }
  14043. };
  14044. /**
  14045. * Set the z offset to apply to current rendering
  14046. * @param value defines the offset to apply
  14047. */
  14048. Engine.prototype.setZOffset = function (value) {
  14049. this._depthCullingState.zOffset = value;
  14050. };
  14051. /**
  14052. * Gets the current value of the zOffset
  14053. * @returns the current zOffset state
  14054. */
  14055. Engine.prototype.getZOffset = function () {
  14056. return this._depthCullingState.zOffset;
  14057. };
  14058. /**
  14059. * Enable or disable depth buffering
  14060. * @param enable defines the state to set
  14061. */
  14062. Engine.prototype.setDepthBuffer = function (enable) {
  14063. this._depthCullingState.depthTest = enable;
  14064. };
  14065. /**
  14066. * Gets a boolean indicating if depth writing is enabled
  14067. * @returns the current depth writing state
  14068. */
  14069. Engine.prototype.getDepthWrite = function () {
  14070. return this._depthCullingState.depthMask;
  14071. };
  14072. /**
  14073. * Enable or disable depth writing
  14074. * @param enable defines the state to set
  14075. */
  14076. Engine.prototype.setDepthWrite = function (enable) {
  14077. this._depthCullingState.depthMask = enable;
  14078. };
  14079. /**
  14080. * Enable or disable color writing
  14081. * @param enable defines the state to set
  14082. */
  14083. Engine.prototype.setColorWrite = function (enable) {
  14084. this._gl.colorMask(enable, enable, enable, enable);
  14085. this._colorWrite = enable;
  14086. };
  14087. /**
  14088. * Gets a boolean indicating if color writing is enabled
  14089. * @returns the current color writing state
  14090. */
  14091. Engine.prototype.getColorWrite = function () {
  14092. return this._colorWrite;
  14093. };
  14094. /**
  14095. * Sets alpha constants used by some alpha blending modes
  14096. * @param r defines the red component
  14097. * @param g defines the green component
  14098. * @param b defines the blue component
  14099. * @param a defines the alpha component
  14100. */
  14101. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14102. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14103. };
  14104. /**
  14105. * Sets the current alpha mode
  14106. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14107. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14108. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14109. */
  14110. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14111. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14112. if (this._alphaMode === mode) {
  14113. return;
  14114. }
  14115. switch (mode) {
  14116. case Engine.ALPHA_DISABLE:
  14117. this._alphaState.alphaBlend = false;
  14118. break;
  14119. case Engine.ALPHA_PREMULTIPLIED:
  14120. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14121. this._alphaState.alphaBlend = true;
  14122. break;
  14123. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14124. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14125. this._alphaState.alphaBlend = true;
  14126. break;
  14127. case Engine.ALPHA_COMBINE:
  14128. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14129. this._alphaState.alphaBlend = true;
  14130. break;
  14131. case Engine.ALPHA_ONEONE:
  14132. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14133. this._alphaState.alphaBlend = true;
  14134. break;
  14135. case Engine.ALPHA_ADD:
  14136. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14137. this._alphaState.alphaBlend = true;
  14138. break;
  14139. case Engine.ALPHA_SUBTRACT:
  14140. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14141. this._alphaState.alphaBlend = true;
  14142. break;
  14143. case Engine.ALPHA_MULTIPLY:
  14144. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14145. this._alphaState.alphaBlend = true;
  14146. break;
  14147. case Engine.ALPHA_MAXIMIZED:
  14148. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14149. this._alphaState.alphaBlend = true;
  14150. break;
  14151. case Engine.ALPHA_INTERPOLATE:
  14152. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14153. this._alphaState.alphaBlend = true;
  14154. break;
  14155. case Engine.ALPHA_SCREENMODE:
  14156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14157. this._alphaState.alphaBlend = true;
  14158. break;
  14159. }
  14160. if (!noDepthWriteChange) {
  14161. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14162. }
  14163. this._alphaMode = mode;
  14164. };
  14165. /**
  14166. * Gets the current alpha mode
  14167. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14168. * @returns the current alpha mode
  14169. */
  14170. Engine.prototype.getAlphaMode = function () {
  14171. return this._alphaMode;
  14172. };
  14173. // Textures
  14174. /**
  14175. * Clears the list of texture accessible through engine.
  14176. * This can help preventing texture load conflict due to name collision.
  14177. */
  14178. Engine.prototype.clearInternalTexturesCache = function () {
  14179. this._internalTexturesCache = [];
  14180. };
  14181. /**
  14182. * Force the entire cache to be cleared
  14183. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14184. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14185. */
  14186. Engine.prototype.wipeCaches = function (bruteForce) {
  14187. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14188. return;
  14189. }
  14190. this._currentEffect = null;
  14191. this._unpackFlipYCached = null;
  14192. this._viewportCached.x = 0;
  14193. this._viewportCached.y = 0;
  14194. this._viewportCached.z = 0;
  14195. this._viewportCached.w = 0;
  14196. if (bruteForce) {
  14197. this.resetTextureCache();
  14198. this._currentProgram = null;
  14199. this._stencilState.reset();
  14200. this._depthCullingState.reset();
  14201. this.setDepthFunctionToLessOrEqual();
  14202. this._alphaState.reset();
  14203. }
  14204. this._resetVertexBufferBinding();
  14205. this._cachedIndexBuffer = null;
  14206. this._cachedEffectForVertexBuffers = null;
  14207. this._unbindVertexArrayObject();
  14208. this.bindIndexBuffer(null);
  14209. };
  14210. /**
  14211. * Set the compressed texture format to use, based on the formats you have, and the formats
  14212. * supported by the hardware / browser.
  14213. *
  14214. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14215. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14216. * to API arguments needed to compressed textures. This puts the burden on the container
  14217. * generator to house the arcane code for determining these for current & future formats.
  14218. *
  14219. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14220. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14221. *
  14222. * Note: The result of this call is not taken into account when a texture is base64.
  14223. *
  14224. * @param formatsAvailable defines the list of those format families you have created
  14225. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14226. *
  14227. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14228. * @returns The extension selected.
  14229. */
  14230. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14231. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14232. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14233. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14234. return this._textureFormatInUse = this._texturesSupported[i];
  14235. }
  14236. }
  14237. }
  14238. // actively set format to nothing, to allow this to be called more than once
  14239. // and possibly fail the 2nd time
  14240. this._textureFormatInUse = null;
  14241. return null;
  14242. };
  14243. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14244. var gl = this._gl;
  14245. var magFilter = gl.NEAREST;
  14246. var minFilter = gl.NEAREST;
  14247. switch (samplingMode) {
  14248. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14249. magFilter = gl.LINEAR;
  14250. if (generateMipMaps) {
  14251. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14252. }
  14253. else {
  14254. minFilter = gl.LINEAR;
  14255. }
  14256. break;
  14257. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14258. magFilter = gl.LINEAR;
  14259. if (generateMipMaps) {
  14260. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14261. }
  14262. else {
  14263. minFilter = gl.LINEAR;
  14264. }
  14265. break;
  14266. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14267. magFilter = gl.NEAREST;
  14268. if (generateMipMaps) {
  14269. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14270. }
  14271. else {
  14272. minFilter = gl.NEAREST;
  14273. }
  14274. break;
  14275. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14276. magFilter = gl.NEAREST;
  14277. if (generateMipMaps) {
  14278. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14279. }
  14280. else {
  14281. minFilter = gl.NEAREST;
  14282. }
  14283. break;
  14284. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14285. magFilter = gl.NEAREST;
  14286. if (generateMipMaps) {
  14287. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14288. }
  14289. else {
  14290. minFilter = gl.LINEAR;
  14291. }
  14292. break;
  14293. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14294. magFilter = gl.NEAREST;
  14295. if (generateMipMaps) {
  14296. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14297. }
  14298. else {
  14299. minFilter = gl.LINEAR;
  14300. }
  14301. break;
  14302. case Engine.TEXTURE_NEAREST_LINEAR:
  14303. magFilter = gl.NEAREST;
  14304. minFilter = gl.LINEAR;
  14305. break;
  14306. case Engine.TEXTURE_NEAREST_NEAREST:
  14307. magFilter = gl.NEAREST;
  14308. minFilter = gl.NEAREST;
  14309. break;
  14310. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14311. magFilter = gl.LINEAR;
  14312. if (generateMipMaps) {
  14313. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14314. }
  14315. else {
  14316. minFilter = gl.NEAREST;
  14317. }
  14318. break;
  14319. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14320. magFilter = gl.LINEAR;
  14321. if (generateMipMaps) {
  14322. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14323. }
  14324. else {
  14325. minFilter = gl.NEAREST;
  14326. }
  14327. break;
  14328. case Engine.TEXTURE_LINEAR_LINEAR:
  14329. magFilter = gl.LINEAR;
  14330. minFilter = gl.LINEAR;
  14331. break;
  14332. case Engine.TEXTURE_LINEAR_NEAREST:
  14333. magFilter = gl.LINEAR;
  14334. minFilter = gl.NEAREST;
  14335. break;
  14336. }
  14337. return {
  14338. min: minFilter,
  14339. mag: magFilter
  14340. };
  14341. };
  14342. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14343. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14344. var img;
  14345. var onload = function () {
  14346. loadedImages[index] = img;
  14347. loadedImages._internalCount++;
  14348. if (scene) {
  14349. scene._removePendingData(img);
  14350. }
  14351. if (loadedImages._internalCount === 6) {
  14352. onfinish(loadedImages);
  14353. }
  14354. };
  14355. var onerror = function (message, exception) {
  14356. if (scene) {
  14357. scene._removePendingData(img);
  14358. }
  14359. if (onErrorCallBack) {
  14360. onErrorCallBack(message, exception);
  14361. }
  14362. };
  14363. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14364. if (scene) {
  14365. scene._addPendingData(img);
  14366. }
  14367. };
  14368. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14369. if (onError === void 0) { onError = null; }
  14370. var loadedImages = [];
  14371. loadedImages._internalCount = 0;
  14372. for (var index = 0; index < 6; index++) {
  14373. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14374. }
  14375. };
  14376. ;
  14377. /** @hidden */
  14378. Engine.prototype._createTexture = function () {
  14379. var texture = this._gl.createTexture();
  14380. if (!texture) {
  14381. throw new Error("Unable to create texture");
  14382. }
  14383. return texture;
  14384. };
  14385. /**
  14386. * Usually called from BABYLON.Texture.ts.
  14387. * Passed information to create a WebGLTexture
  14388. * @param urlArg defines a value which contains one of the following:
  14389. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14390. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14391. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14392. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14393. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14394. * @param scene needed for loading to the correct scene
  14395. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14396. * @param onLoad optional callback to be called upon successful completion
  14397. * @param onError optional callback to be called upon failure
  14398. * @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
  14399. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14400. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14401. * @param forcedExtension defines the extension to use to pick the right loader
  14402. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14403. */
  14404. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14405. var _this = this;
  14406. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14407. if (onLoad === void 0) { onLoad = null; }
  14408. if (onError === void 0) { onError = null; }
  14409. if (buffer === void 0) { buffer = null; }
  14410. if (fallback === void 0) { fallback = null; }
  14411. if (format === void 0) { format = null; }
  14412. if (forcedExtension === void 0) { forcedExtension = null; }
  14413. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14414. var fromData = url.substr(0, 5) === "data:";
  14415. var fromBlob = url.substr(0, 5) === "blob:";
  14416. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14417. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14418. // establish the file extension, if possible
  14419. var lastDot = url.lastIndexOf('.');
  14420. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14421. var loader = null;
  14422. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14423. var availableLoader = _a[_i];
  14424. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14425. loader = availableLoader;
  14426. break;
  14427. }
  14428. }
  14429. if (loader) {
  14430. url = loader.transformUrl(url, this._textureFormatInUse);
  14431. }
  14432. if (scene) {
  14433. scene._addPendingData(texture);
  14434. }
  14435. texture.url = url;
  14436. texture.generateMipMaps = !noMipmap;
  14437. texture.samplingMode = samplingMode;
  14438. texture.invertY = invertY;
  14439. if (!this._doNotHandleContextLost) {
  14440. // Keep a link to the buffer only if we plan to handle context lost
  14441. texture._buffer = buffer;
  14442. }
  14443. var onLoadObserver = null;
  14444. if (onLoad && !fallback) {
  14445. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14446. }
  14447. if (!fallback)
  14448. this._internalTexturesCache.push(texture);
  14449. var onInternalError = function (message, exception) {
  14450. if (scene) {
  14451. scene._removePendingData(texture);
  14452. }
  14453. var customFallback = false;
  14454. if (loader) {
  14455. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14456. if (fallbackUrl) {
  14457. // Add Back
  14458. customFallback = true;
  14459. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14460. }
  14461. }
  14462. if (!customFallback) {
  14463. if (onLoadObserver) {
  14464. texture.onLoadedObservable.remove(onLoadObserver);
  14465. }
  14466. if (BABYLON.Tools.UseFallbackTexture) {
  14467. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14468. }
  14469. }
  14470. if (onError) {
  14471. onError(message || "Unknown error", exception);
  14472. }
  14473. };
  14474. // processing for non-image formats
  14475. if (loader) {
  14476. var callback = function (data) {
  14477. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14478. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14479. done();
  14480. return false;
  14481. }, samplingMode);
  14482. });
  14483. };
  14484. if (!buffer) {
  14485. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14486. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14487. });
  14488. }
  14489. else {
  14490. callback(buffer);
  14491. }
  14492. }
  14493. else {
  14494. var onload = function (img) {
  14495. if (fromBlob && !_this._doNotHandleContextLost) {
  14496. // We need to store the image if we need to rebuild the texture
  14497. // in case of a webgl context lost
  14498. texture._buffer = img;
  14499. }
  14500. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14501. var gl = _this._gl;
  14502. var isPot = (img.width === potWidth && img.height === potHeight);
  14503. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14504. if (isPot) {
  14505. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14506. return false;
  14507. }
  14508. var maxTextureSize = _this._caps.maxTextureSize;
  14509. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14510. _this._prepareWorkingCanvas();
  14511. if (!_this._workingCanvas || !_this._workingContext) {
  14512. return false;
  14513. }
  14514. _this._workingCanvas.width = potWidth;
  14515. _this._workingCanvas.height = potHeight;
  14516. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14517. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14518. texture.width = potWidth;
  14519. texture.height = potHeight;
  14520. return false;
  14521. }
  14522. else {
  14523. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14524. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14525. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14526. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14527. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14528. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14531. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14532. _this._releaseTexture(source_1);
  14533. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14534. continuationCallback();
  14535. });
  14536. }
  14537. return true;
  14538. }, samplingMode);
  14539. };
  14540. if (!fromData || isBase64) {
  14541. if (buffer instanceof HTMLImageElement) {
  14542. onload(buffer);
  14543. }
  14544. else {
  14545. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14546. }
  14547. }
  14548. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14549. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14550. }
  14551. else {
  14552. onload(buffer);
  14553. }
  14554. }
  14555. return texture;
  14556. };
  14557. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14558. var _this = this;
  14559. var rtt = this.createRenderTargetTexture({
  14560. width: destination.width,
  14561. height: destination.height,
  14562. }, {
  14563. generateMipMaps: false,
  14564. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14565. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14566. generateDepthBuffer: false,
  14567. generateStencilBuffer: false
  14568. });
  14569. if (!this._rescalePostProcess) {
  14570. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14571. }
  14572. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14573. _this._rescalePostProcess.onApply = function (effect) {
  14574. effect._bindTexture("textureSampler", source);
  14575. };
  14576. var hostingScene = scene;
  14577. if (!hostingScene) {
  14578. hostingScene = _this.scenes[_this.scenes.length - 1];
  14579. }
  14580. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14581. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14582. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14583. _this.unBindFramebuffer(rtt);
  14584. _this._releaseTexture(rtt);
  14585. if (onComplete) {
  14586. onComplete();
  14587. }
  14588. });
  14589. };
  14590. /**
  14591. * Update a raw texture
  14592. * @param texture defines the texture to update
  14593. * @param data defines the data to store in the texture
  14594. * @param format defines the format of the data
  14595. * @param invertY defines if data must be stored with Y axis inverted
  14596. * @param compression defines the compression used (null by default)
  14597. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14598. */
  14599. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14600. if (compression === void 0) { compression = null; }
  14601. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14602. if (!texture) {
  14603. return;
  14604. }
  14605. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14606. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14607. // babylon's internalFormat but gl's texImage2D format
  14608. var internalFormat = this._getInternalFormat(format);
  14609. var textureType = this._getWebGLTextureType(type);
  14610. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14611. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14612. if (!this._doNotHandleContextLost) {
  14613. texture._bufferView = data;
  14614. texture.format = format;
  14615. texture.type = type;
  14616. texture.invertY = invertY;
  14617. texture._compression = compression;
  14618. }
  14619. if (texture.width % 4 !== 0) {
  14620. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14621. }
  14622. if (compression && data) {
  14623. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14624. }
  14625. else {
  14626. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14627. }
  14628. if (texture.generateMipMaps) {
  14629. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14630. }
  14631. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14632. // this.resetTextureCache();
  14633. texture.isReady = true;
  14634. };
  14635. /**
  14636. * Creates a raw texture
  14637. * @param data defines the data to store in the texture
  14638. * @param width defines the width of the texture
  14639. * @param height defines the height of the texture
  14640. * @param format defines the format of the data
  14641. * @param generateMipMaps defines if the engine should generate the mip levels
  14642. * @param invertY defines if data must be stored with Y axis inverted
  14643. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14644. * @param compression defines the compression used (null by default)
  14645. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14646. * @returns the raw texture inside an InternalTexture
  14647. */
  14648. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14649. if (compression === void 0) { compression = null; }
  14650. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14651. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14652. texture.baseWidth = width;
  14653. texture.baseHeight = height;
  14654. texture.width = width;
  14655. texture.height = height;
  14656. texture.format = format;
  14657. texture.generateMipMaps = generateMipMaps;
  14658. texture.samplingMode = samplingMode;
  14659. texture.invertY = invertY;
  14660. texture._compression = compression;
  14661. texture.type = type;
  14662. if (!this._doNotHandleContextLost) {
  14663. texture._bufferView = data;
  14664. }
  14665. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14666. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14667. // Filters
  14668. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14669. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14670. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14671. if (generateMipMaps) {
  14672. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14673. }
  14674. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14675. this._internalTexturesCache.push(texture);
  14676. return texture;
  14677. };
  14678. /** @hidden */
  14679. Engine.prototype._unpackFlipY = function (value) {
  14680. if (this._unpackFlipYCached !== value) {
  14681. this._unpackFlipYCached = value;
  14682. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14683. }
  14684. };
  14685. /** @hidden */
  14686. Engine.prototype._getUnpackAlignement = function () {
  14687. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14688. };
  14689. /**
  14690. * Creates a dynamic texture
  14691. * @param width defines the width of the texture
  14692. * @param height defines the height of the texture
  14693. * @param generateMipMaps defines if the engine should generate the mip levels
  14694. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14695. * @returns the dynamic texture inside an InternalTexture
  14696. */
  14697. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14698. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14699. texture.baseWidth = width;
  14700. texture.baseHeight = height;
  14701. if (generateMipMaps) {
  14702. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14703. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14704. }
  14705. // this.resetTextureCache();
  14706. texture.width = width;
  14707. texture.height = height;
  14708. texture.isReady = false;
  14709. texture.generateMipMaps = generateMipMaps;
  14710. texture.samplingMode = samplingMode;
  14711. this.updateTextureSamplingMode(samplingMode, texture);
  14712. this._internalTexturesCache.push(texture);
  14713. return texture;
  14714. };
  14715. /**
  14716. * Update the sampling mode of a given texture
  14717. * @param samplingMode defines the required sampling mode
  14718. * @param texture defines the texture to update
  14719. */
  14720. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14721. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14722. if (texture.isCube) {
  14723. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14724. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14725. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14726. }
  14727. else if (texture.is3D) {
  14728. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14729. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14730. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14731. }
  14732. else {
  14733. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14734. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14735. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14736. }
  14737. texture.samplingMode = samplingMode;
  14738. };
  14739. /**
  14740. * Update the content of a dynamic texture
  14741. * @param texture defines the texture to update
  14742. * @param canvas defines the canvas containing the source
  14743. * @param invertY defines if data must be stored with Y axis inverted
  14744. * @param premulAlpha defines if alpha is stored as premultiplied
  14745. * @param format defines the format of the data
  14746. */
  14747. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14748. if (premulAlpha === void 0) { premulAlpha = false; }
  14749. if (!texture) {
  14750. return;
  14751. }
  14752. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14753. this._unpackFlipY(invertY);
  14754. if (premulAlpha) {
  14755. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14756. }
  14757. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14758. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14759. if (texture.generateMipMaps) {
  14760. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14761. }
  14762. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14763. if (premulAlpha) {
  14764. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14765. }
  14766. texture.isReady = true;
  14767. };
  14768. /**
  14769. * Update a video texture
  14770. * @param texture defines the texture to update
  14771. * @param video defines the video element to use
  14772. * @param invertY defines if data must be stored with Y axis inverted
  14773. */
  14774. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14775. if (!texture || texture._isDisabled) {
  14776. return;
  14777. }
  14778. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14779. this._unpackFlipY(!invertY); // Video are upside down by default
  14780. try {
  14781. // Testing video texture support
  14782. if (this._videoTextureSupported === undefined) {
  14783. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14784. if (this._gl.getError() !== 0) {
  14785. this._videoTextureSupported = false;
  14786. }
  14787. else {
  14788. this._videoTextureSupported = true;
  14789. }
  14790. }
  14791. // Copy video through the current working canvas if video texture is not supported
  14792. if (!this._videoTextureSupported) {
  14793. if (!texture._workingCanvas) {
  14794. texture._workingCanvas = document.createElement("canvas");
  14795. var context = texture._workingCanvas.getContext("2d");
  14796. if (!context) {
  14797. throw new Error("Unable to get 2d context");
  14798. }
  14799. texture._workingContext = context;
  14800. texture._workingCanvas.width = texture.width;
  14801. texture._workingCanvas.height = texture.height;
  14802. }
  14803. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14804. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14805. }
  14806. else {
  14807. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14808. }
  14809. if (texture.generateMipMaps) {
  14810. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14811. }
  14812. if (!wasPreviouslyBound) {
  14813. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14814. }
  14815. // this.resetTextureCache();
  14816. texture.isReady = true;
  14817. }
  14818. catch (ex) {
  14819. // Something unexpected
  14820. // Let's disable the texture
  14821. texture._isDisabled = true;
  14822. }
  14823. };
  14824. /**
  14825. * Updates a depth texture Comparison Mode and Function.
  14826. * If the comparison Function is equal to 0, the mode will be set to none.
  14827. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14828. * @param texture The texture to set the comparison function for
  14829. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14830. */
  14831. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14832. if (this.webGLVersion === 1) {
  14833. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14834. return;
  14835. }
  14836. var gl = this._gl;
  14837. if (texture.isCube) {
  14838. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14839. if (comparisonFunction === 0) {
  14840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14841. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14842. }
  14843. else {
  14844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14846. }
  14847. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14848. }
  14849. else {
  14850. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14851. if (comparisonFunction === 0) {
  14852. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14854. }
  14855. else {
  14856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14858. }
  14859. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14860. }
  14861. texture._comparisonFunction = comparisonFunction;
  14862. };
  14863. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14864. var width = size.width || size;
  14865. var height = size.height || size;
  14866. internalTexture.baseWidth = width;
  14867. internalTexture.baseHeight = height;
  14868. internalTexture.width = width;
  14869. internalTexture.height = height;
  14870. internalTexture.isReady = true;
  14871. internalTexture.samples = 1;
  14872. internalTexture.generateMipMaps = false;
  14873. internalTexture._generateDepthBuffer = true;
  14874. internalTexture._generateStencilBuffer = generateStencil;
  14875. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14876. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14877. internalTexture._comparisonFunction = comparisonFunction;
  14878. var gl = this._gl;
  14879. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14880. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14881. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14882. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14883. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14884. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14885. if (comparisonFunction === 0) {
  14886. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14887. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14888. }
  14889. else {
  14890. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14891. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14892. }
  14893. };
  14894. /**
  14895. * Creates a depth stencil texture.
  14896. * This is only available in WebGL 2 or with the depth texture extension available.
  14897. * @param size The size of face edge in the texture.
  14898. * @param options The options defining the texture.
  14899. * @returns The texture
  14900. */
  14901. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14902. if (options.isCube) {
  14903. var width = size.width || size;
  14904. return this._createDepthStencilCubeTexture(width, options);
  14905. }
  14906. else {
  14907. return this._createDepthStencilTexture(size, options);
  14908. }
  14909. };
  14910. /**
  14911. * Creates a depth stencil texture.
  14912. * This is only available in WebGL 2 or with the depth texture extension available.
  14913. * @param size The size of face edge in the texture.
  14914. * @param options The options defining the texture.
  14915. * @returns The texture
  14916. */
  14917. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14918. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14919. if (!this._caps.depthTextureExtension) {
  14920. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14921. return internalTexture;
  14922. }
  14923. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14924. var gl = this._gl;
  14925. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14926. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14927. if (this.webGLVersion > 1) {
  14928. if (internalOptions.generateStencil) {
  14929. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14930. }
  14931. else {
  14932. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14933. }
  14934. }
  14935. else {
  14936. if (internalOptions.generateStencil) {
  14937. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14938. }
  14939. else {
  14940. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14941. }
  14942. }
  14943. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14944. return internalTexture;
  14945. };
  14946. /**
  14947. * Creates a depth stencil cube texture.
  14948. * This is only available in WebGL 2.
  14949. * @param size The size of face edge in the cube texture.
  14950. * @param options The options defining the cube texture.
  14951. * @returns The cube texture
  14952. */
  14953. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14954. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14955. internalTexture.isCube = true;
  14956. if (this.webGLVersion === 1) {
  14957. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14958. return internalTexture;
  14959. }
  14960. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14961. var gl = this._gl;
  14962. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14963. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14964. // Create the depth/stencil buffer
  14965. for (var face = 0; face < 6; face++) {
  14966. if (internalOptions.generateStencil) {
  14967. 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);
  14968. }
  14969. else {
  14970. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14971. }
  14972. }
  14973. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14974. return internalTexture;
  14975. };
  14976. /**
  14977. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14978. * @param renderTarget The render target to set the frame buffer for
  14979. */
  14980. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14981. // Create the framebuffer
  14982. var internalTexture = renderTarget.getInternalTexture();
  14983. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14984. return;
  14985. }
  14986. var gl = this._gl;
  14987. var depthStencilTexture = renderTarget.depthStencilTexture;
  14988. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14989. if (depthStencilTexture.isCube) {
  14990. if (depthStencilTexture._generateStencilBuffer) {
  14991. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14992. }
  14993. else {
  14994. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14995. }
  14996. }
  14997. else {
  14998. if (depthStencilTexture._generateStencilBuffer) {
  14999. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15000. }
  15001. else {
  15002. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15003. }
  15004. }
  15005. this.bindUnboundFramebuffer(null);
  15006. };
  15007. /**
  15008. * Creates a new render target texture
  15009. * @param size defines the size of the texture
  15010. * @param options defines the options used to create the texture
  15011. * @returns a new render target texture stored in an InternalTexture
  15012. */
  15013. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15014. var fullOptions = new RenderTargetCreationOptions();
  15015. if (options !== undefined && typeof options === "object") {
  15016. fullOptions.generateMipMaps = options.generateMipMaps;
  15017. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15018. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15019. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15020. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15021. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15022. }
  15023. else {
  15024. fullOptions.generateMipMaps = options;
  15025. fullOptions.generateDepthBuffer = true;
  15026. fullOptions.generateStencilBuffer = false;
  15027. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15028. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15029. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15030. }
  15031. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15032. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15033. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15034. }
  15035. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15036. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15037. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15038. }
  15039. var gl = this._gl;
  15040. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15041. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15042. var width = size.width || size;
  15043. var height = size.height || size;
  15044. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15045. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15046. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15047. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15048. }
  15049. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15050. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15052. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15053. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15054. // Create the framebuffer
  15055. var currentFrameBuffer = this._currentFramebuffer;
  15056. var framebuffer = gl.createFramebuffer();
  15057. this.bindUnboundFramebuffer(framebuffer);
  15058. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15059. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15060. if (fullOptions.generateMipMaps) {
  15061. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15062. }
  15063. // Unbind
  15064. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15065. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15066. this.bindUnboundFramebuffer(currentFrameBuffer);
  15067. texture._framebuffer = framebuffer;
  15068. texture.baseWidth = width;
  15069. texture.baseHeight = height;
  15070. texture.width = width;
  15071. texture.height = height;
  15072. texture.isReady = true;
  15073. texture.samples = 1;
  15074. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15075. texture.samplingMode = fullOptions.samplingMode;
  15076. texture.type = fullOptions.type;
  15077. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15078. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15079. // this.resetTextureCache();
  15080. this._internalTexturesCache.push(texture);
  15081. return texture;
  15082. };
  15083. /**
  15084. * Create a multi render target texture
  15085. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15086. * @param size defines the size of the texture
  15087. * @param options defines the creation options
  15088. * @returns the cube texture as an InternalTexture
  15089. */
  15090. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15091. var generateMipMaps = false;
  15092. var generateDepthBuffer = true;
  15093. var generateStencilBuffer = false;
  15094. var generateDepthTexture = false;
  15095. var textureCount = 1;
  15096. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15097. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15098. var types = new Array();
  15099. var samplingModes = new Array();
  15100. if (options !== undefined) {
  15101. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15102. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15103. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15104. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15105. textureCount = options.textureCount || 1;
  15106. if (options.types) {
  15107. types = options.types;
  15108. }
  15109. if (options.samplingModes) {
  15110. samplingModes = options.samplingModes;
  15111. }
  15112. }
  15113. var gl = this._gl;
  15114. // Create the framebuffer
  15115. var framebuffer = gl.createFramebuffer();
  15116. this.bindUnboundFramebuffer(framebuffer);
  15117. var width = size.width || size;
  15118. var height = size.height || size;
  15119. var textures = [];
  15120. var attachments = [];
  15121. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15122. for (var i = 0; i < textureCount; i++) {
  15123. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15124. var type = types[i] || defaultType;
  15125. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15126. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15127. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15128. }
  15129. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15130. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15131. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15132. }
  15133. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15134. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15135. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15136. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15137. }
  15138. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15139. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15140. textures.push(texture);
  15141. attachments.push(attachment);
  15142. gl.activeTexture(gl["TEXTURE" + i]);
  15143. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15145. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15146. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15148. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15149. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15150. if (generateMipMaps) {
  15151. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15152. }
  15153. // Unbind
  15154. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15155. texture._framebuffer = framebuffer;
  15156. texture._depthStencilBuffer = depthStencilBuffer;
  15157. texture.baseWidth = width;
  15158. texture.baseHeight = height;
  15159. texture.width = width;
  15160. texture.height = height;
  15161. texture.isReady = true;
  15162. texture.samples = 1;
  15163. texture.generateMipMaps = generateMipMaps;
  15164. texture.samplingMode = samplingMode;
  15165. texture.type = type;
  15166. texture._generateDepthBuffer = generateDepthBuffer;
  15167. texture._generateStencilBuffer = generateStencilBuffer;
  15168. texture._attachments = attachments;
  15169. this._internalTexturesCache.push(texture);
  15170. }
  15171. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15172. // Depth texture
  15173. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15174. gl.activeTexture(gl.TEXTURE0);
  15175. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15180. 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);
  15181. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15182. depthTexture._framebuffer = framebuffer;
  15183. depthTexture.baseWidth = width;
  15184. depthTexture.baseHeight = height;
  15185. depthTexture.width = width;
  15186. depthTexture.height = height;
  15187. depthTexture.isReady = true;
  15188. depthTexture.samples = 1;
  15189. depthTexture.generateMipMaps = generateMipMaps;
  15190. depthTexture.samplingMode = gl.NEAREST;
  15191. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15192. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15193. textures.push(depthTexture);
  15194. this._internalTexturesCache.push(depthTexture);
  15195. }
  15196. gl.drawBuffers(attachments);
  15197. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15198. this.bindUnboundFramebuffer(null);
  15199. this.resetTextureCache();
  15200. return textures;
  15201. };
  15202. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15203. if (samples === void 0) { samples = 1; }
  15204. var depthStencilBuffer = null;
  15205. var gl = this._gl;
  15206. // Create the depth/stencil buffer
  15207. if (generateStencilBuffer) {
  15208. depthStencilBuffer = gl.createRenderbuffer();
  15209. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15210. if (samples > 1) {
  15211. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15212. }
  15213. else {
  15214. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15215. }
  15216. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15217. }
  15218. else if (generateDepthBuffer) {
  15219. depthStencilBuffer = gl.createRenderbuffer();
  15220. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15221. if (samples > 1) {
  15222. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15223. }
  15224. else {
  15225. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15226. }
  15227. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15228. }
  15229. return depthStencilBuffer;
  15230. };
  15231. /**
  15232. * Updates the sample count of a render target texture
  15233. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15234. * @param texture defines the texture to update
  15235. * @param samples defines the sample count to set
  15236. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15237. */
  15238. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15239. if (this.webGLVersion < 2 || !texture) {
  15240. return 1;
  15241. }
  15242. if (texture.samples === samples) {
  15243. return samples;
  15244. }
  15245. var gl = this._gl;
  15246. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15247. // Dispose previous render buffers
  15248. if (texture._depthStencilBuffer) {
  15249. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15250. texture._depthStencilBuffer = null;
  15251. }
  15252. if (texture._MSAAFramebuffer) {
  15253. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15254. texture._MSAAFramebuffer = null;
  15255. }
  15256. if (texture._MSAARenderBuffer) {
  15257. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15258. texture._MSAARenderBuffer = null;
  15259. }
  15260. if (samples > 1) {
  15261. var framebuffer = gl.createFramebuffer();
  15262. if (!framebuffer) {
  15263. throw new Error("Unable to create multi sampled framebuffer");
  15264. }
  15265. texture._MSAAFramebuffer = framebuffer;
  15266. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15267. var colorRenderbuffer = gl.createRenderbuffer();
  15268. if (!colorRenderbuffer) {
  15269. throw new Error("Unable to create multi sampled framebuffer");
  15270. }
  15271. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15272. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15273. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15274. texture._MSAARenderBuffer = colorRenderbuffer;
  15275. }
  15276. else {
  15277. this.bindUnboundFramebuffer(texture._framebuffer);
  15278. }
  15279. texture.samples = samples;
  15280. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15281. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15282. this.bindUnboundFramebuffer(null);
  15283. return samples;
  15284. };
  15285. /**
  15286. * Update the sample count for a given multiple render target texture
  15287. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15288. * @param textures defines the textures to update
  15289. * @param samples defines the sample count to set
  15290. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15291. */
  15292. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15293. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15294. return 1;
  15295. }
  15296. if (textures[0].samples === samples) {
  15297. return samples;
  15298. }
  15299. var gl = this._gl;
  15300. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15301. // Dispose previous render buffers
  15302. if (textures[0]._depthStencilBuffer) {
  15303. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15304. textures[0]._depthStencilBuffer = null;
  15305. }
  15306. if (textures[0]._MSAAFramebuffer) {
  15307. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15308. textures[0]._MSAAFramebuffer = null;
  15309. }
  15310. for (var i = 0; i < textures.length; i++) {
  15311. if (textures[i]._MSAARenderBuffer) {
  15312. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15313. textures[i]._MSAARenderBuffer = null;
  15314. }
  15315. }
  15316. if (samples > 1) {
  15317. var framebuffer = gl.createFramebuffer();
  15318. if (!framebuffer) {
  15319. throw new Error("Unable to create multi sampled framebuffer");
  15320. }
  15321. this.bindUnboundFramebuffer(framebuffer);
  15322. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15323. var attachments = [];
  15324. for (var i = 0; i < textures.length; i++) {
  15325. var texture = textures[i];
  15326. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15327. var colorRenderbuffer = gl.createRenderbuffer();
  15328. if (!colorRenderbuffer) {
  15329. throw new Error("Unable to create multi sampled framebuffer");
  15330. }
  15331. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15332. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15333. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15334. texture._MSAAFramebuffer = framebuffer;
  15335. texture._MSAARenderBuffer = colorRenderbuffer;
  15336. texture.samples = samples;
  15337. texture._depthStencilBuffer = depthStencilBuffer;
  15338. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15339. attachments.push(attachment);
  15340. }
  15341. gl.drawBuffers(attachments);
  15342. }
  15343. else {
  15344. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15345. }
  15346. this.bindUnboundFramebuffer(null);
  15347. return samples;
  15348. };
  15349. /** @hidden */
  15350. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15351. if (faceIndex === void 0) { faceIndex = 0; }
  15352. if (lod === void 0) { lod = 0; }
  15353. var gl = this._gl;
  15354. var target = gl.TEXTURE_2D;
  15355. if (texture.isCube) {
  15356. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15357. }
  15358. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15359. };
  15360. /** @hidden */
  15361. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15362. if (faceIndex === void 0) { faceIndex = 0; }
  15363. if (lod === void 0) { lod = 0; }
  15364. var gl = this._gl;
  15365. var textureType = this._getWebGLTextureType(texture.type);
  15366. var format = this._getInternalFormat(texture.format);
  15367. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15368. this._unpackFlipY(texture.invertY);
  15369. var target = gl.TEXTURE_2D;
  15370. if (texture.isCube) {
  15371. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15372. }
  15373. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15374. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15375. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15376. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15377. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15378. };
  15379. /** @hidden */
  15380. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15381. if (faceIndex === void 0) { faceIndex = 0; }
  15382. if (lod === void 0) { lod = 0; }
  15383. var gl = this._gl;
  15384. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15385. this._bindTextureDirectly(bindTarget, texture, true);
  15386. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15387. this._bindTextureDirectly(bindTarget, null, true);
  15388. };
  15389. /** @hidden */
  15390. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15391. if (faceIndex === void 0) { faceIndex = 0; }
  15392. if (lod === void 0) { lod = 0; }
  15393. var gl = this._gl;
  15394. var textureType = this._getWebGLTextureType(texture.type);
  15395. var format = this._getInternalFormat(texture.format);
  15396. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15397. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15398. this._bindTextureDirectly(bindTarget, texture, true);
  15399. this._unpackFlipY(texture.invertY);
  15400. var target = gl.TEXTURE_2D;
  15401. if (texture.isCube) {
  15402. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15403. }
  15404. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15405. this._bindTextureDirectly(bindTarget, null, true);
  15406. };
  15407. /**
  15408. * Creates a new render target cube texture
  15409. * @param size defines the size of the texture
  15410. * @param options defines the options used to create the texture
  15411. * @returns a new render target cube texture stored in an InternalTexture
  15412. */
  15413. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15414. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15415. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15416. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15417. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15418. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15419. }
  15420. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15421. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15422. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15423. }
  15424. var gl = this._gl;
  15425. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15426. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15427. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15428. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15429. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15430. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15431. }
  15432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15433. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15434. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15436. for (var face = 0; face < 6; face++) {
  15437. 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);
  15438. }
  15439. // Create the framebuffer
  15440. var framebuffer = gl.createFramebuffer();
  15441. this.bindUnboundFramebuffer(framebuffer);
  15442. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15443. // MipMaps
  15444. if (fullOptions.generateMipMaps) {
  15445. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15446. }
  15447. // Unbind
  15448. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15449. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15450. this.bindUnboundFramebuffer(null);
  15451. texture._framebuffer = framebuffer;
  15452. texture.width = size;
  15453. texture.height = size;
  15454. texture.isReady = true;
  15455. texture.isCube = true;
  15456. texture.samples = 1;
  15457. texture.generateMipMaps = fullOptions.generateMipMaps;
  15458. texture.samplingMode = fullOptions.samplingMode;
  15459. texture.type = fullOptions.type;
  15460. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15461. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15462. this._internalTexturesCache.push(texture);
  15463. return texture;
  15464. };
  15465. /**
  15466. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15467. * @param rootUrl defines the url where the file to load is located
  15468. * @param scene defines the current scene
  15469. * @param lodScale defines scale to apply to the mip map selection
  15470. * @param lodOffset defines offset to apply to the mip map selection
  15471. * @param onLoad defines an optional callback raised when the texture is loaded
  15472. * @param onError defines an optional callback raised if there is an issue to load the texture
  15473. * @param format defines the format of the data
  15474. * @param forcedExtension defines the extension to use to pick the right loader
  15475. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15476. * @returns the cube texture as an InternalTexture
  15477. */
  15478. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15479. var _this = this;
  15480. if (onLoad === void 0) { onLoad = null; }
  15481. if (onError === void 0) { onError = null; }
  15482. if (forcedExtension === void 0) { forcedExtension = null; }
  15483. if (createPolynomials === void 0) { createPolynomials = true; }
  15484. var callback = function (loadData) {
  15485. if (!loadData) {
  15486. if (onLoad) {
  15487. onLoad(null);
  15488. }
  15489. return;
  15490. }
  15491. var texture = loadData.texture;
  15492. if (!createPolynomials) {
  15493. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15494. }
  15495. else if (loadData.info.sphericalPolynomial) {
  15496. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15497. }
  15498. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15499. if (_this._caps.textureLOD) {
  15500. // Do not add extra process if texture lod is supported.
  15501. if (onLoad) {
  15502. onLoad(texture);
  15503. }
  15504. return;
  15505. }
  15506. var mipSlices = 3;
  15507. var gl = _this._gl;
  15508. var width = loadData.width;
  15509. if (!width) {
  15510. return;
  15511. }
  15512. var textures = [];
  15513. for (var i = 0; i < mipSlices; i++) {
  15514. //compute LOD from even spacing in smoothness (matching shader calculation)
  15515. var smoothness = i / (mipSlices - 1);
  15516. var roughness = 1 - smoothness;
  15517. var minLODIndex = lodOffset; // roughness = 0
  15518. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15519. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15520. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15521. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15522. glTextureFromLod.type = texture.type;
  15523. glTextureFromLod.format = texture.format;
  15524. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15525. glTextureFromLod.height = glTextureFromLod.width;
  15526. glTextureFromLod.isCube = true;
  15527. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15530. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15531. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15532. if (loadData.isDDS) {
  15533. var info = loadData.info;
  15534. var data = loadData.data;
  15535. _this._unpackFlipY(info.isCompressed);
  15536. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15537. }
  15538. else {
  15539. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15540. }
  15541. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15542. // Wrap in a base texture for easy binding.
  15543. var lodTexture = new BABYLON.BaseTexture(scene);
  15544. lodTexture.isCube = true;
  15545. lodTexture._texture = glTextureFromLod;
  15546. glTextureFromLod.isReady = true;
  15547. textures.push(lodTexture);
  15548. }
  15549. texture._lodTextureHigh = textures[2];
  15550. texture._lodTextureMid = textures[1];
  15551. texture._lodTextureLow = textures[0];
  15552. if (onLoad) {
  15553. onLoad(texture);
  15554. }
  15555. };
  15556. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15557. };
  15558. /**
  15559. * Creates a cube texture
  15560. * @param rootUrl defines the url where the files to load is located
  15561. * @param scene defines the current scene
  15562. * @param files defines the list of files to load (1 per face)
  15563. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15564. * @param onLoad defines an optional callback raised when the texture is loaded
  15565. * @param onError defines an optional callback raised if there is an issue to load the texture
  15566. * @param format defines the format of the data
  15567. * @param forcedExtension defines the extension to use to pick the right loader
  15568. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15569. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15570. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15571. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15572. * @returns the cube texture as an InternalTexture
  15573. */
  15574. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15575. var _this = this;
  15576. if (onLoad === void 0) { onLoad = null; }
  15577. if (onError === void 0) { onError = null; }
  15578. if (forcedExtension === void 0) { forcedExtension = null; }
  15579. if (createPolynomials === void 0) { createPolynomials = false; }
  15580. if (lodScale === void 0) { lodScale = 0; }
  15581. if (lodOffset === void 0) { lodOffset = 0; }
  15582. if (fallback === void 0) { fallback = null; }
  15583. var gl = this._gl;
  15584. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15585. texture.isCube = true;
  15586. texture.url = rootUrl;
  15587. texture.generateMipMaps = !noMipmap;
  15588. texture._lodGenerationScale = lodScale;
  15589. texture._lodGenerationOffset = lodOffset;
  15590. if (!this._doNotHandleContextLost) {
  15591. texture._extension = forcedExtension;
  15592. texture._files = files;
  15593. }
  15594. var lastDot = rootUrl.lastIndexOf('.');
  15595. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15596. var loader = null;
  15597. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15598. var availableLoader = _a[_i];
  15599. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15600. loader = availableLoader;
  15601. break;
  15602. }
  15603. }
  15604. var onInternalError = function (request, exception) {
  15605. if (loader) {
  15606. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15607. if (fallbackUrl) {
  15608. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15609. }
  15610. }
  15611. if (onError && request) {
  15612. onError(request.status + " " + request.statusText, exception);
  15613. }
  15614. };
  15615. if (loader) {
  15616. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15617. var onloaddata = function (data) {
  15618. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15619. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15620. };
  15621. if (files && files.length === 6) {
  15622. if (loader.supportCascades) {
  15623. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15624. }
  15625. else if (onError) {
  15626. onError("Textures type does not support cascades.");
  15627. }
  15628. }
  15629. else {
  15630. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15631. }
  15632. }
  15633. else {
  15634. if (!files) {
  15635. throw new Error("Cannot load cubemap because files were not defined");
  15636. }
  15637. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15638. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15639. var height = width;
  15640. _this._prepareWorkingCanvas();
  15641. if (!_this._workingCanvas || !_this._workingContext) {
  15642. return;
  15643. }
  15644. _this._workingCanvas.width = width;
  15645. _this._workingCanvas.height = height;
  15646. var faces = [
  15647. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15648. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15649. ];
  15650. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15651. _this._unpackFlipY(false);
  15652. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15653. for (var index = 0; index < faces.length; index++) {
  15654. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15655. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15656. }
  15657. if (!noMipmap) {
  15658. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15659. }
  15660. _this._setCubeMapTextureParams(!noMipmap);
  15661. texture.width = width;
  15662. texture.height = height;
  15663. texture.isReady = true;
  15664. if (format) {
  15665. texture.format = format;
  15666. }
  15667. texture.onLoadedObservable.notifyObservers(texture);
  15668. texture.onLoadedObservable.clear();
  15669. if (onLoad) {
  15670. onLoad();
  15671. }
  15672. }, files, onError);
  15673. }
  15674. this._internalTexturesCache.push(texture);
  15675. return texture;
  15676. };
  15677. /**
  15678. * @hidden
  15679. */
  15680. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15681. var gl = this._gl;
  15682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15686. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15687. // this.resetTextureCache();
  15688. };
  15689. /**
  15690. * Update a raw cube texture
  15691. * @param texture defines the texture to udpdate
  15692. * @param data defines the data to store
  15693. * @param format defines the data format
  15694. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15695. * @param invertY defines if data must be stored with Y axis inverted
  15696. * @param compression defines the compression used (null by default)
  15697. * @param level defines which level of the texture to update
  15698. */
  15699. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15700. if (compression === void 0) { compression = null; }
  15701. if (level === void 0) { level = 0; }
  15702. texture._bufferViewArray = data;
  15703. texture.format = format;
  15704. texture.type = type;
  15705. texture.invertY = invertY;
  15706. texture._compression = compression;
  15707. var gl = this._gl;
  15708. var textureType = this._getWebGLTextureType(type);
  15709. var internalFormat = this._getInternalFormat(format);
  15710. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15711. var needConversion = false;
  15712. if (internalFormat === gl.RGB) {
  15713. internalFormat = gl.RGBA;
  15714. needConversion = true;
  15715. }
  15716. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15717. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15718. if (texture.width % 4 !== 0) {
  15719. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15720. }
  15721. // Data are known to be in +X +Y +Z -X -Y -Z
  15722. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15723. var faceData = data[faceIndex];
  15724. if (compression) {
  15725. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15726. }
  15727. else {
  15728. if (needConversion) {
  15729. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15730. }
  15731. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15732. }
  15733. }
  15734. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15735. if (isPot && texture.generateMipMaps && level === 0) {
  15736. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15737. }
  15738. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15739. // this.resetTextureCache();
  15740. texture.isReady = true;
  15741. };
  15742. /**
  15743. * Creates a new raw cube texture
  15744. * @param data defines the array of data to use to create each face
  15745. * @param size defines the size of the textures
  15746. * @param format defines the format of the data
  15747. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15748. * @param generateMipMaps defines if the engine should generate the mip levels
  15749. * @param invertY defines if data must be stored with Y axis inverted
  15750. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15751. * @param compression defines the compression used (null by default)
  15752. * @returns the cube texture as an InternalTexture
  15753. */
  15754. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15755. if (compression === void 0) { compression = null; }
  15756. var gl = this._gl;
  15757. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15758. texture.isCube = true;
  15759. texture.format = format;
  15760. texture.type = type;
  15761. if (!this._doNotHandleContextLost) {
  15762. texture._bufferViewArray = data;
  15763. }
  15764. var textureType = this._getWebGLTextureType(type);
  15765. var internalFormat = this._getInternalFormat(format);
  15766. if (internalFormat === gl.RGB) {
  15767. internalFormat = gl.RGBA;
  15768. }
  15769. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15770. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15771. generateMipMaps = false;
  15772. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15773. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15774. }
  15775. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15776. generateMipMaps = false;
  15777. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15778. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15779. }
  15780. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15781. generateMipMaps = false;
  15782. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15783. }
  15784. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15785. generateMipMaps = false;
  15786. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15787. }
  15788. var width = size;
  15789. var height = width;
  15790. texture.width = width;
  15791. texture.height = height;
  15792. // Double check on POT to generate Mips.
  15793. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15794. if (!isPot) {
  15795. generateMipMaps = false;
  15796. }
  15797. // Upload data if needed. The texture won't be ready until then.
  15798. if (data) {
  15799. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15800. }
  15801. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15802. // Filters
  15803. if (data && generateMipMaps) {
  15804. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15805. }
  15806. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15809. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15810. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15811. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15812. texture.generateMipMaps = generateMipMaps;
  15813. return texture;
  15814. };
  15815. /**
  15816. * Creates a new raw cube texture from a specified url
  15817. * @param url defines the url where the data is located
  15818. * @param scene defines the current scene
  15819. * @param size defines the size of the textures
  15820. * @param format defines the format of the data
  15821. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15822. * @param noMipmap defines if the engine should avoid generating the mip levels
  15823. * @param callback defines a callback used to extract texture data from loaded data
  15824. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15825. * @param onLoad defines a callback called when texture is loaded
  15826. * @param onError defines a callback called if there is an error
  15827. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15828. * @param invertY defines if data must be stored with Y axis inverted
  15829. * @returns the cube texture as an InternalTexture
  15830. */
  15831. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15832. var _this = this;
  15833. if (onLoad === void 0) { onLoad = null; }
  15834. if (onError === void 0) { onError = null; }
  15835. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15836. if (invertY === void 0) { invertY = false; }
  15837. var gl = this._gl;
  15838. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15839. scene._addPendingData(texture);
  15840. texture.url = url;
  15841. this._internalTexturesCache.push(texture);
  15842. var onerror = function (request, exception) {
  15843. scene._removePendingData(texture);
  15844. if (onError && request) {
  15845. onError(request.status + " " + request.statusText, exception);
  15846. }
  15847. };
  15848. var internalCallback = function (data) {
  15849. var width = texture.width;
  15850. var faceDataArrays = callback(data);
  15851. if (!faceDataArrays) {
  15852. return;
  15853. }
  15854. if (mipmapGenerator) {
  15855. var textureType = _this._getWebGLTextureType(type);
  15856. var internalFormat = _this._getInternalFormat(format);
  15857. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15858. var needConversion = false;
  15859. if (internalFormat === gl.RGB) {
  15860. internalFormat = gl.RGBA;
  15861. needConversion = true;
  15862. }
  15863. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15864. _this._unpackFlipY(false);
  15865. var mipData = mipmapGenerator(faceDataArrays);
  15866. for (var level = 0; level < mipData.length; level++) {
  15867. var mipSize = width >> level;
  15868. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15869. var mipFaceData = mipData[level][faceIndex];
  15870. if (needConversion) {
  15871. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15872. }
  15873. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15874. }
  15875. }
  15876. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15877. }
  15878. else {
  15879. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15880. }
  15881. texture.isReady = true;
  15882. // this.resetTextureCache();
  15883. scene._removePendingData(texture);
  15884. if (onLoad) {
  15885. onLoad();
  15886. }
  15887. };
  15888. this._loadFile(url, function (data) {
  15889. internalCallback(data);
  15890. }, undefined, scene.database, true, onerror);
  15891. return texture;
  15892. };
  15893. ;
  15894. /**
  15895. * Update a raw 3D texture
  15896. * @param texture defines the texture to update
  15897. * @param data defines the data to store
  15898. * @param format defines the data format
  15899. * @param invertY defines if data must be stored with Y axis inverted
  15900. * @param compression defines the used compression (can be null)
  15901. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15902. */
  15903. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15904. if (compression === void 0) { compression = null; }
  15905. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15906. var internalType = this._getWebGLTextureType(textureType);
  15907. var internalFormat = this._getInternalFormat(format);
  15908. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15909. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15910. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15911. if (!this._doNotHandleContextLost) {
  15912. texture._bufferView = data;
  15913. texture.format = format;
  15914. texture.invertY = invertY;
  15915. texture._compression = compression;
  15916. }
  15917. if (texture.width % 4 !== 0) {
  15918. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15919. }
  15920. if (compression && data) {
  15921. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15922. }
  15923. else {
  15924. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15925. }
  15926. if (texture.generateMipMaps) {
  15927. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15928. }
  15929. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15930. // this.resetTextureCache();
  15931. texture.isReady = true;
  15932. };
  15933. /**
  15934. * Creates a new raw 3D texture
  15935. * @param data defines the data used to create the texture
  15936. * @param width defines the width of the texture
  15937. * @param height defines the height of the texture
  15938. * @param depth defines the depth of the texture
  15939. * @param format defines the format of the texture
  15940. * @param generateMipMaps defines if the engine must generate mip levels
  15941. * @param invertY defines if data must be stored with Y axis inverted
  15942. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15943. * @param compression defines the compressed used (can be null)
  15944. * @param textureType defines the compressed used (can be null)
  15945. * @returns a new raw 3D texture (stored in an InternalTexture)
  15946. */
  15947. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15948. if (compression === void 0) { compression = null; }
  15949. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15950. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15951. texture.baseWidth = width;
  15952. texture.baseHeight = height;
  15953. texture.baseDepth = depth;
  15954. texture.width = width;
  15955. texture.height = height;
  15956. texture.depth = depth;
  15957. texture.format = format;
  15958. texture.type = textureType;
  15959. texture.generateMipMaps = generateMipMaps;
  15960. texture.samplingMode = samplingMode;
  15961. texture.is3D = true;
  15962. if (!this._doNotHandleContextLost) {
  15963. texture._bufferView = data;
  15964. }
  15965. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15966. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15967. // Filters
  15968. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15969. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15970. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15971. if (generateMipMaps) {
  15972. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15973. }
  15974. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15975. this._internalTexturesCache.push(texture);
  15976. return texture;
  15977. };
  15978. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15979. var gl = this._gl;
  15980. if (!gl) {
  15981. return;
  15982. }
  15983. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15986. if (!noMipmap && !isCompressed) {
  15987. gl.generateMipmap(gl.TEXTURE_2D);
  15988. }
  15989. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15990. // this.resetTextureCache();
  15991. if (scene) {
  15992. scene._removePendingData(texture);
  15993. }
  15994. texture.onLoadedObservable.notifyObservers(texture);
  15995. texture.onLoadedObservable.clear();
  15996. };
  15997. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15998. var _this = this;
  15999. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16000. var maxTextureSize = this.getCaps().maxTextureSize;
  16001. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16002. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16003. var gl = this._gl;
  16004. if (!gl) {
  16005. return;
  16006. }
  16007. if (!texture._webGLTexture) {
  16008. // this.resetTextureCache();
  16009. if (scene) {
  16010. scene._removePendingData(texture);
  16011. }
  16012. return;
  16013. }
  16014. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16015. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16016. texture.baseWidth = width;
  16017. texture.baseHeight = height;
  16018. texture.width = potWidth;
  16019. texture.height = potHeight;
  16020. texture.isReady = true;
  16021. if (processFunction(potWidth, potHeight, function () {
  16022. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16023. })) {
  16024. // Returning as texture needs extra async steps
  16025. return;
  16026. }
  16027. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16028. };
  16029. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16030. // Create new RGBA data container.
  16031. var rgbaData;
  16032. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16033. rgbaData = new Float32Array(width * height * 4);
  16034. }
  16035. else {
  16036. rgbaData = new Uint32Array(width * height * 4);
  16037. }
  16038. // Convert each pixel.
  16039. for (var x = 0; x < width; x++) {
  16040. for (var y = 0; y < height; y++) {
  16041. var index = (y * width + x) * 3;
  16042. var newIndex = (y * width + x) * 4;
  16043. // Map Old Value to new value.
  16044. rgbaData[newIndex + 0] = rgbData[index + 0];
  16045. rgbaData[newIndex + 1] = rgbData[index + 1];
  16046. rgbaData[newIndex + 2] = rgbData[index + 2];
  16047. // Add fully opaque alpha channel.
  16048. rgbaData[newIndex + 3] = 1;
  16049. }
  16050. }
  16051. return rgbaData;
  16052. };
  16053. /** @hidden */
  16054. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16055. var gl = this._gl;
  16056. if (texture._framebuffer) {
  16057. gl.deleteFramebuffer(texture._framebuffer);
  16058. texture._framebuffer = null;
  16059. }
  16060. if (texture._depthStencilBuffer) {
  16061. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16062. texture._depthStencilBuffer = null;
  16063. }
  16064. if (texture._MSAAFramebuffer) {
  16065. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16066. texture._MSAAFramebuffer = null;
  16067. }
  16068. if (texture._MSAARenderBuffer) {
  16069. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16070. texture._MSAARenderBuffer = null;
  16071. }
  16072. };
  16073. /** @hidden */
  16074. Engine.prototype._releaseTexture = function (texture) {
  16075. var gl = this._gl;
  16076. this._releaseFramebufferObjects(texture);
  16077. gl.deleteTexture(texture._webGLTexture);
  16078. // Unbind channels
  16079. this.unbindAllTextures();
  16080. var index = this._internalTexturesCache.indexOf(texture);
  16081. if (index !== -1) {
  16082. this._internalTexturesCache.splice(index, 1);
  16083. }
  16084. // Integrated fixed lod samplers.
  16085. if (texture._lodTextureHigh) {
  16086. texture._lodTextureHigh.dispose();
  16087. }
  16088. if (texture._lodTextureMid) {
  16089. texture._lodTextureMid.dispose();
  16090. }
  16091. if (texture._lodTextureLow) {
  16092. texture._lodTextureLow.dispose();
  16093. }
  16094. // Set output texture of post process to null if the texture has been released/disposed
  16095. this.scenes.forEach(function (scene) {
  16096. scene.postProcesses.forEach(function (postProcess) {
  16097. if (postProcess._outputTexture == texture) {
  16098. postProcess._outputTexture = null;
  16099. }
  16100. });
  16101. scene.cameras.forEach(function (camera) {
  16102. camera._postProcesses.forEach(function (postProcess) {
  16103. if (postProcess) {
  16104. if (postProcess._outputTexture == texture) {
  16105. postProcess._outputTexture = null;
  16106. }
  16107. }
  16108. });
  16109. });
  16110. });
  16111. };
  16112. Engine.prototype.setProgram = function (program) {
  16113. if (this._currentProgram !== program) {
  16114. this._gl.useProgram(program);
  16115. this._currentProgram = program;
  16116. }
  16117. };
  16118. /**
  16119. * Binds an effect to the webGL context
  16120. * @param effect defines the effect to bind
  16121. */
  16122. Engine.prototype.bindSamplers = function (effect) {
  16123. this.setProgram(effect.getProgram());
  16124. var samplers = effect.getSamplers();
  16125. for (var index = 0; index < samplers.length; index++) {
  16126. var uniform = effect.getUniform(samplers[index]);
  16127. if (uniform) {
  16128. this._boundUniforms[index] = uniform;
  16129. }
  16130. }
  16131. this._currentEffect = null;
  16132. };
  16133. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16134. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16135. return;
  16136. }
  16137. // Remove
  16138. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16139. // Bind last to it
  16140. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16141. // Bind to dummy
  16142. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16143. };
  16144. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16145. if (!internalTexture) {
  16146. return -1;
  16147. }
  16148. internalTexture._initialSlot = channel;
  16149. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16150. if (channel !== internalTexture._designatedSlot) {
  16151. this._textureCollisions.addCount(1, false);
  16152. }
  16153. }
  16154. else {
  16155. if (channel !== internalTexture._designatedSlot) {
  16156. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16157. return internalTexture._designatedSlot;
  16158. }
  16159. else {
  16160. // No slot for this texture, let's pick a new one (if we find a free slot)
  16161. if (this._nextFreeTextureSlots.length) {
  16162. return this._nextFreeTextureSlots[0];
  16163. }
  16164. // We need to recycle the oldest bound texture, sorry.
  16165. this._textureCollisions.addCount(1, false);
  16166. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16167. }
  16168. }
  16169. }
  16170. return channel;
  16171. };
  16172. Engine.prototype._linkTrackers = function (previous, next) {
  16173. previous.next = next;
  16174. next.previous = previous;
  16175. };
  16176. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16177. var currentSlot = internalTexture._designatedSlot;
  16178. if (currentSlot === -1) {
  16179. return -1;
  16180. }
  16181. internalTexture._designatedSlot = -1;
  16182. if (this.disableTextureBindingOptimization) {
  16183. return -1;
  16184. }
  16185. // Remove from bound list
  16186. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16187. // Free the slot
  16188. this._boundTexturesCache[currentSlot] = null;
  16189. this._nextFreeTextureSlots.push(currentSlot);
  16190. return currentSlot;
  16191. };
  16192. Engine.prototype._activateCurrentTexture = function () {
  16193. if (this._currentTextureChannel !== this._activeChannel) {
  16194. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16195. this._currentTextureChannel = this._activeChannel;
  16196. }
  16197. };
  16198. /** @hidden */
  16199. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16200. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16201. if (force === void 0) { force = false; }
  16202. var wasPreviouslyBound = false;
  16203. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16204. this._activeChannel = texture._designatedSlot;
  16205. }
  16206. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16207. var isTextureForRendering = texture && texture._initialSlot > -1;
  16208. if (currentTextureBound !== texture || force) {
  16209. if (currentTextureBound) {
  16210. this._removeDesignatedSlot(currentTextureBound);
  16211. }
  16212. this._activateCurrentTexture();
  16213. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16214. this._boundTexturesCache[this._activeChannel] = texture;
  16215. if (texture) {
  16216. if (!this.disableTextureBindingOptimization) {
  16217. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16218. if (slotIndex > -1) {
  16219. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16220. }
  16221. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16222. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16223. }
  16224. texture._designatedSlot = this._activeChannel;
  16225. }
  16226. }
  16227. else if (forTextureDataUpdate) {
  16228. wasPreviouslyBound = true;
  16229. this._activateCurrentTexture();
  16230. }
  16231. if (isTextureForRendering && !forTextureDataUpdate) {
  16232. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16233. }
  16234. return wasPreviouslyBound;
  16235. };
  16236. /** @hidden */
  16237. Engine.prototype._bindTexture = function (channel, texture) {
  16238. if (channel < 0) {
  16239. return;
  16240. }
  16241. if (texture) {
  16242. channel = this._getCorrectTextureChannel(channel, texture);
  16243. }
  16244. this._activeChannel = channel;
  16245. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16246. };
  16247. /**
  16248. * Sets a texture to the webGL context from a postprocess
  16249. * @param channel defines the channel to use
  16250. * @param postProcess defines the source postprocess
  16251. */
  16252. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16253. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16254. };
  16255. /**
  16256. * Binds the output of the passed in post process to the texture channel specified
  16257. * @param channel The channel the texture should be bound to
  16258. * @param postProcess The post process which's output should be bound
  16259. */
  16260. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16261. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16262. };
  16263. /**
  16264. * Unbind all textures from the webGL context
  16265. */
  16266. Engine.prototype.unbindAllTextures = function () {
  16267. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16268. this._activeChannel = channel;
  16269. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16270. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16271. if (this.webGLVersion > 1) {
  16272. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16273. }
  16274. }
  16275. };
  16276. /**
  16277. * Sets a texture to the according uniform.
  16278. * @param channel The texture channel
  16279. * @param uniform The uniform to set
  16280. * @param texture The texture to apply
  16281. */
  16282. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16283. if (channel < 0) {
  16284. return;
  16285. }
  16286. if (uniform) {
  16287. this._boundUniforms[channel] = uniform;
  16288. }
  16289. this._setTexture(channel, texture);
  16290. };
  16291. /**
  16292. * Sets a depth stencil texture from a render target to the according uniform.
  16293. * @param channel The texture channel
  16294. * @param uniform The uniform to set
  16295. * @param texture The render target texture containing the depth stencil texture to apply
  16296. */
  16297. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16298. if (channel < 0) {
  16299. return;
  16300. }
  16301. if (uniform) {
  16302. this._boundUniforms[channel] = uniform;
  16303. }
  16304. if (!texture || !texture.depthStencilTexture) {
  16305. this._setTexture(channel, null);
  16306. }
  16307. else {
  16308. this._setTexture(channel, texture, false, true);
  16309. }
  16310. };
  16311. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16312. var uniform = this._boundUniforms[sourceSlot];
  16313. if (uniform._currentState === destination) {
  16314. return;
  16315. }
  16316. this._gl.uniform1i(uniform, destination);
  16317. uniform._currentState = destination;
  16318. };
  16319. Engine.prototype._getTextureWrapMode = function (mode) {
  16320. switch (mode) {
  16321. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16322. return this._gl.REPEAT;
  16323. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16324. return this._gl.CLAMP_TO_EDGE;
  16325. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16326. return this._gl.MIRRORED_REPEAT;
  16327. }
  16328. return this._gl.REPEAT;
  16329. };
  16330. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16331. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16332. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16333. // Not ready?
  16334. if (!texture) {
  16335. if (this._boundTexturesCache[channel] != null) {
  16336. this._activeChannel = channel;
  16337. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16338. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16339. if (this.webGLVersion > 1) {
  16340. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16341. }
  16342. }
  16343. return false;
  16344. }
  16345. // Video
  16346. if (texture.video) {
  16347. this._activeChannel = channel;
  16348. texture.update();
  16349. }
  16350. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16351. texture.delayLoad();
  16352. return false;
  16353. }
  16354. var internalTexture;
  16355. if (depthStencilTexture) {
  16356. internalTexture = texture.depthStencilTexture;
  16357. }
  16358. else if (texture.isReady()) {
  16359. internalTexture = texture.getInternalTexture();
  16360. }
  16361. else if (texture.isCube) {
  16362. internalTexture = this.emptyCubeTexture;
  16363. }
  16364. else if (texture.is3D) {
  16365. internalTexture = this.emptyTexture3D;
  16366. }
  16367. else {
  16368. internalTexture = this.emptyTexture;
  16369. }
  16370. if (!isPartOfTextureArray) {
  16371. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16372. }
  16373. var needToBind = true;
  16374. if (this._boundTexturesCache[channel] === internalTexture) {
  16375. this._moveBoundTextureOnTop(internalTexture);
  16376. if (!isPartOfTextureArray) {
  16377. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16378. }
  16379. needToBind = false;
  16380. }
  16381. this._activeChannel = channel;
  16382. if (internalTexture && internalTexture.is3D) {
  16383. if (needToBind) {
  16384. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16385. }
  16386. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16387. internalTexture._cachedWrapU = texture.wrapU;
  16388. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16389. }
  16390. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16391. internalTexture._cachedWrapV = texture.wrapV;
  16392. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16393. }
  16394. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16395. internalTexture._cachedWrapR = texture.wrapR;
  16396. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16397. }
  16398. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16399. }
  16400. else if (internalTexture && internalTexture.isCube) {
  16401. if (needToBind) {
  16402. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16403. }
  16404. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16405. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16406. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16407. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16408. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16409. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16410. }
  16411. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16412. }
  16413. else {
  16414. if (needToBind) {
  16415. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16416. }
  16417. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16418. internalTexture._cachedWrapU = texture.wrapU;
  16419. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16420. }
  16421. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16422. internalTexture._cachedWrapV = texture.wrapV;
  16423. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16424. }
  16425. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16426. }
  16427. return true;
  16428. };
  16429. /**
  16430. * Sets an array of texture to the webGL context
  16431. * @param channel defines the channel where the texture array must be set
  16432. * @param uniform defines the associated uniform location
  16433. * @param textures defines the array of textures to bind
  16434. */
  16435. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16436. if (channel < 0 || !uniform) {
  16437. return;
  16438. }
  16439. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16440. this._textureUnits = new Int32Array(textures.length);
  16441. }
  16442. for (var i = 0; i < textures.length; i++) {
  16443. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16444. }
  16445. this._gl.uniform1iv(uniform, this._textureUnits);
  16446. for (var index = 0; index < textures.length; index++) {
  16447. this._setTexture(this._textureUnits[index], textures[index], true);
  16448. }
  16449. };
  16450. /** @hidden */
  16451. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16452. var internalTexture = texture.getInternalTexture();
  16453. if (!internalTexture) {
  16454. return;
  16455. }
  16456. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16457. var value = texture.anisotropicFilteringLevel;
  16458. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16459. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16460. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16461. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16462. }
  16463. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16464. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16465. internalTexture._cachedAnisotropicFilteringLevel = value;
  16466. }
  16467. };
  16468. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16469. this._bindTextureDirectly(target, texture, true, true);
  16470. this._gl.texParameterf(target, parameter, value);
  16471. };
  16472. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16473. if (texture) {
  16474. this._bindTextureDirectly(target, texture, true, true);
  16475. }
  16476. this._gl.texParameteri(target, parameter, value);
  16477. };
  16478. /**
  16479. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16480. * @param x defines the x coordinate of the rectangle where pixels must be read
  16481. * @param y defines the y coordinate of the rectangle where pixels must be read
  16482. * @param width defines the width of the rectangle where pixels must be read
  16483. * @param height defines the height of the rectangle where pixels must be read
  16484. * @returns a Uint8Array containing RGBA colors
  16485. */
  16486. Engine.prototype.readPixels = function (x, y, width, height) {
  16487. var data = new Uint8Array(height * width * 4);
  16488. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16489. return data;
  16490. };
  16491. /**
  16492. * Add an externaly attached data from its key.
  16493. * This method call will fail and return false, if such key already exists.
  16494. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16495. * @param key the unique key that identifies the data
  16496. * @param data the data object to associate to the key for this Engine instance
  16497. * @return true if no such key were already present and the data was added successfully, false otherwise
  16498. */
  16499. Engine.prototype.addExternalData = function (key, data) {
  16500. if (!this._externalData) {
  16501. this._externalData = new BABYLON.StringDictionary();
  16502. }
  16503. return this._externalData.add(key, data);
  16504. };
  16505. /**
  16506. * Get an externaly attached data from its key
  16507. * @param key the unique key that identifies the data
  16508. * @return the associated data, if present (can be null), or undefined if not present
  16509. */
  16510. Engine.prototype.getExternalData = function (key) {
  16511. if (!this._externalData) {
  16512. this._externalData = new BABYLON.StringDictionary();
  16513. }
  16514. return this._externalData.get(key);
  16515. };
  16516. /**
  16517. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16518. * @param key the unique key that identifies the data
  16519. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16520. * @return the associated data, can be null if the factory returned null.
  16521. */
  16522. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16523. if (!this._externalData) {
  16524. this._externalData = new BABYLON.StringDictionary();
  16525. }
  16526. return this._externalData.getOrAddWithFactory(key, factory);
  16527. };
  16528. /**
  16529. * Remove an externaly attached data from the Engine instance
  16530. * @param key the unique key that identifies the data
  16531. * @return true if the data was successfully removed, false if it doesn't exist
  16532. */
  16533. Engine.prototype.removeExternalData = function (key) {
  16534. if (!this._externalData) {
  16535. this._externalData = new BABYLON.StringDictionary();
  16536. }
  16537. return this._externalData.remove(key);
  16538. };
  16539. /**
  16540. * Unbind all vertex attributes from the webGL context
  16541. */
  16542. Engine.prototype.unbindAllAttributes = function () {
  16543. if (this._mustWipeVertexAttributes) {
  16544. this._mustWipeVertexAttributes = false;
  16545. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16546. this._gl.disableVertexAttribArray(i);
  16547. this._vertexAttribArraysEnabled[i] = false;
  16548. this._currentBufferPointers[i].active = false;
  16549. }
  16550. return;
  16551. }
  16552. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16553. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16554. continue;
  16555. }
  16556. this._gl.disableVertexAttribArray(i);
  16557. this._vertexAttribArraysEnabled[i] = false;
  16558. this._currentBufferPointers[i].active = false;
  16559. }
  16560. };
  16561. /**
  16562. * 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
  16563. */
  16564. Engine.prototype.releaseEffects = function () {
  16565. for (var name in this._compiledEffects) {
  16566. this._deleteProgram(this._compiledEffects[name]._program);
  16567. }
  16568. this._compiledEffects = {};
  16569. };
  16570. /**
  16571. * Dispose and release all associated resources
  16572. */
  16573. Engine.prototype.dispose = function () {
  16574. this.hideLoadingUI();
  16575. this.stopRenderLoop();
  16576. // Release postProcesses
  16577. while (this.postProcesses.length) {
  16578. this.postProcesses[0].dispose();
  16579. }
  16580. // Empty texture
  16581. if (this._emptyTexture) {
  16582. this._releaseTexture(this._emptyTexture);
  16583. this._emptyTexture = null;
  16584. }
  16585. if (this._emptyCubeTexture) {
  16586. this._releaseTexture(this._emptyCubeTexture);
  16587. this._emptyCubeTexture = null;
  16588. }
  16589. // Rescale PP
  16590. if (this._rescalePostProcess) {
  16591. this._rescalePostProcess.dispose();
  16592. }
  16593. // Release scenes
  16594. while (this.scenes.length) {
  16595. this.scenes[0].dispose();
  16596. }
  16597. // Release audio engine
  16598. if (Engine.audioEngine) {
  16599. Engine.audioEngine.dispose();
  16600. }
  16601. // Release effects
  16602. this.releaseEffects();
  16603. // Unbind
  16604. this.unbindAllAttributes();
  16605. this._boundUniforms = [];
  16606. if (this._dummyFramebuffer) {
  16607. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16608. }
  16609. //WebVR
  16610. this.disableVR();
  16611. // Events
  16612. if (BABYLON.Tools.IsWindowObjectExist()) {
  16613. window.removeEventListener("blur", this._onBlur);
  16614. window.removeEventListener("focus", this._onFocus);
  16615. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16616. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16617. if (this._renderingCanvas) {
  16618. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16619. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16620. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16621. if (!this._doNotHandleContextLost) {
  16622. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16623. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16624. }
  16625. }
  16626. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16627. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16628. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16629. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16630. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16631. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16632. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16633. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16634. if (this._onVrDisplayConnect) {
  16635. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16636. if (this._onVrDisplayDisconnect) {
  16637. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16638. }
  16639. if (this._onVrDisplayPresentChange) {
  16640. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16641. }
  16642. this._onVrDisplayConnect = null;
  16643. this._onVrDisplayDisconnect = null;
  16644. }
  16645. }
  16646. // Remove from Instances
  16647. var index = Engine.Instances.indexOf(this);
  16648. if (index >= 0) {
  16649. Engine.Instances.splice(index, 1);
  16650. }
  16651. this._workingCanvas = null;
  16652. this._workingContext = null;
  16653. this._currentBufferPointers = [];
  16654. this._renderingCanvas = null;
  16655. this._currentProgram = null;
  16656. this._bindedRenderFunction = null;
  16657. this.onResizeObservable.clear();
  16658. this.onCanvasBlurObservable.clear();
  16659. this.onCanvasFocusObservable.clear();
  16660. this.onCanvasPointerOutObservable.clear();
  16661. this.onBeginFrameObservable.clear();
  16662. this.onEndFrameObservable.clear();
  16663. BABYLON.Effect.ResetCache();
  16664. // Abort active requests
  16665. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16666. var request = _a[_i];
  16667. request.abort();
  16668. }
  16669. };
  16670. // Loading screen
  16671. /**
  16672. * Display the loading screen
  16673. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16674. */
  16675. Engine.prototype.displayLoadingUI = function () {
  16676. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16677. return;
  16678. }
  16679. var loadingScreen = this.loadingScreen;
  16680. if (loadingScreen) {
  16681. loadingScreen.displayLoadingUI();
  16682. }
  16683. };
  16684. /**
  16685. * Hide the loading screen
  16686. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16687. */
  16688. Engine.prototype.hideLoadingUI = function () {
  16689. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16690. return;
  16691. }
  16692. var loadingScreen = this.loadingScreen;
  16693. if (loadingScreen) {
  16694. loadingScreen.hideLoadingUI();
  16695. }
  16696. };
  16697. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16698. /**
  16699. * Gets the current loading screen object
  16700. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16701. */
  16702. get: function () {
  16703. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16704. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16705. return this._loadingScreen;
  16706. },
  16707. /**
  16708. * Sets the current loading screen object
  16709. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16710. */
  16711. set: function (loadingScreen) {
  16712. this._loadingScreen = loadingScreen;
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16718. /**
  16719. * Sets the current loading screen text
  16720. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16721. */
  16722. set: function (text) {
  16723. this.loadingScreen.loadingUIText = text;
  16724. },
  16725. enumerable: true,
  16726. configurable: true
  16727. });
  16728. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16729. /**
  16730. * Sets the current loading screen background color
  16731. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16732. */
  16733. set: function (color) {
  16734. this.loadingScreen.loadingUIBackgroundColor = color;
  16735. },
  16736. enumerable: true,
  16737. configurable: true
  16738. });
  16739. /**
  16740. * Attach a new callback raised when context lost event is fired
  16741. * @param callback defines the callback to call
  16742. */
  16743. Engine.prototype.attachContextLostEvent = function (callback) {
  16744. if (this._renderingCanvas) {
  16745. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16746. }
  16747. };
  16748. /**
  16749. * Attach a new callback raised when context restored event is fired
  16750. * @param callback defines the callback to call
  16751. */
  16752. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16753. if (this._renderingCanvas) {
  16754. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16755. }
  16756. };
  16757. /**
  16758. * Gets the source code of the vertex shader associated with a specific webGL program
  16759. * @param program defines the program to use
  16760. * @returns a string containing the source code of the vertex shader associated with the program
  16761. */
  16762. Engine.prototype.getVertexShaderSource = function (program) {
  16763. var shaders = this._gl.getAttachedShaders(program);
  16764. if (!shaders) {
  16765. return null;
  16766. }
  16767. return this._gl.getShaderSource(shaders[0]);
  16768. };
  16769. /**
  16770. * Gets the source code of the fragment shader associated with a specific webGL program
  16771. * @param program defines the program to use
  16772. * @returns a string containing the source code of the fragment shader associated with the program
  16773. */
  16774. Engine.prototype.getFragmentShaderSource = function (program) {
  16775. var shaders = this._gl.getAttachedShaders(program);
  16776. if (!shaders) {
  16777. return null;
  16778. }
  16779. return this._gl.getShaderSource(shaders[1]);
  16780. };
  16781. /**
  16782. * Get the current error code of the webGL context
  16783. * @returns the error code
  16784. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16785. */
  16786. Engine.prototype.getError = function () {
  16787. return this._gl.getError();
  16788. };
  16789. // FPS
  16790. /**
  16791. * Gets the current framerate
  16792. * @returns a number representing the framerate
  16793. */
  16794. Engine.prototype.getFps = function () {
  16795. return this._fps;
  16796. };
  16797. /**
  16798. * Gets the time spent between current and previous frame
  16799. * @returns a number representing the delta time in ms
  16800. */
  16801. Engine.prototype.getDeltaTime = function () {
  16802. return this._deltaTime;
  16803. };
  16804. Engine.prototype._measureFps = function () {
  16805. this._performanceMonitor.sampleFrame();
  16806. this._fps = this._performanceMonitor.averageFPS;
  16807. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16808. };
  16809. /** @hidden */
  16810. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16811. if (faceIndex === void 0) { faceIndex = -1; }
  16812. if (level === void 0) { level = 0; }
  16813. var gl = this._gl;
  16814. if (!this._dummyFramebuffer) {
  16815. var dummy = gl.createFramebuffer();
  16816. if (!dummy) {
  16817. throw new Error("Unable to create dummy framebuffer");
  16818. }
  16819. this._dummyFramebuffer = dummy;
  16820. }
  16821. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16822. if (faceIndex > -1) {
  16823. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16824. }
  16825. else {
  16826. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16827. }
  16828. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16829. var buffer;
  16830. switch (readType) {
  16831. case gl.UNSIGNED_BYTE:
  16832. buffer = new Uint8Array(4 * width * height);
  16833. readType = gl.UNSIGNED_BYTE;
  16834. break;
  16835. default:
  16836. buffer = new Float32Array(4 * width * height);
  16837. readType = gl.FLOAT;
  16838. break;
  16839. }
  16840. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16841. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16842. return buffer;
  16843. };
  16844. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16845. if (this._webGLVersion > 1) {
  16846. return this._caps.colorBufferFloat;
  16847. }
  16848. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16849. };
  16850. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16851. if (this._webGLVersion > 1) {
  16852. return this._caps.colorBufferFloat;
  16853. }
  16854. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16855. };
  16856. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16857. Engine.prototype._canRenderToFramebuffer = function (type) {
  16858. var gl = this._gl;
  16859. //clear existing errors
  16860. while (gl.getError() !== gl.NO_ERROR) { }
  16861. var successful = true;
  16862. var texture = gl.createTexture();
  16863. gl.bindTexture(gl.TEXTURE_2D, texture);
  16864. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16867. var fb = gl.createFramebuffer();
  16868. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16869. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16870. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16871. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16872. successful = successful && (gl.getError() === gl.NO_ERROR);
  16873. //try render by clearing frame buffer's color buffer
  16874. if (successful) {
  16875. gl.clear(gl.COLOR_BUFFER_BIT);
  16876. successful = successful && (gl.getError() === gl.NO_ERROR);
  16877. }
  16878. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16879. if (successful) {
  16880. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16881. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16882. var readFormat = gl.RGBA;
  16883. var readType = gl.UNSIGNED_BYTE;
  16884. var buffer = new Uint8Array(4);
  16885. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16886. successful = successful && (gl.getError() === gl.NO_ERROR);
  16887. }
  16888. //clean up
  16889. gl.deleteTexture(texture);
  16890. gl.deleteFramebuffer(fb);
  16891. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16892. //clear accumulated errors
  16893. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16894. return successful;
  16895. };
  16896. /** @hidden */
  16897. Engine.prototype._getWebGLTextureType = function (type) {
  16898. if (type === Engine.TEXTURETYPE_FLOAT) {
  16899. return this._gl.FLOAT;
  16900. }
  16901. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16902. // Add Half Float Constant.
  16903. return this._gl.HALF_FLOAT_OES;
  16904. }
  16905. return this._gl.UNSIGNED_BYTE;
  16906. };
  16907. ;
  16908. Engine.prototype._getInternalFormat = function (format) {
  16909. var internalFormat = this._gl.RGBA;
  16910. switch (format) {
  16911. case Engine.TEXTUREFORMAT_ALPHA:
  16912. internalFormat = this._gl.ALPHA;
  16913. break;
  16914. case Engine.TEXTUREFORMAT_LUMINANCE:
  16915. internalFormat = this._gl.LUMINANCE;
  16916. break;
  16917. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16918. internalFormat = this._gl.LUMINANCE_ALPHA;
  16919. break;
  16920. case Engine.TEXTUREFORMAT_RGB:
  16921. internalFormat = this._gl.RGB;
  16922. break;
  16923. case Engine.TEXTUREFORMAT_RGBA:
  16924. internalFormat = this._gl.RGBA;
  16925. break;
  16926. case Engine.TEXTUREFORMAT_R:
  16927. internalFormat = this._gl.RED;
  16928. break;
  16929. case Engine.TEXTUREFORMAT_RG:
  16930. internalFormat = this._gl.RG;
  16931. break;
  16932. }
  16933. return internalFormat;
  16934. };
  16935. /** @hidden */
  16936. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16937. if (this._webGLVersion === 1) {
  16938. if (format !== undefined) {
  16939. switch (format) {
  16940. case Engine.TEXTUREFORMAT_LUMINANCE:
  16941. return this._gl.LUMINANCE;
  16942. case Engine.TEXTUREFORMAT_ALPHA:
  16943. return this._gl.ALPHA;
  16944. }
  16945. }
  16946. return this._gl.RGBA;
  16947. }
  16948. if (type === Engine.TEXTURETYPE_FLOAT) {
  16949. if (format !== undefined) {
  16950. switch (format) {
  16951. case Engine.TEXTUREFORMAT_R:
  16952. return this._gl.R32F;
  16953. case Engine.TEXTUREFORMAT_RG:
  16954. return this._gl.RG32F;
  16955. case Engine.TEXTUREFORMAT_RGB:
  16956. return this._gl.RGB32F;
  16957. }
  16958. }
  16959. return this._gl.RGBA32F;
  16960. }
  16961. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16962. if (format) {
  16963. switch (format) {
  16964. case Engine.TEXTUREFORMAT_R:
  16965. return this._gl.R16F;
  16966. case Engine.TEXTUREFORMAT_RG:
  16967. return this._gl.RG16F;
  16968. case Engine.TEXTUREFORMAT_RGB:
  16969. return this._gl.RGB16F;
  16970. }
  16971. }
  16972. return this._gl.RGBA16F;
  16973. }
  16974. if (format !== undefined) {
  16975. switch (format) {
  16976. case Engine.TEXTUREFORMAT_LUMINANCE:
  16977. return this._gl.LUMINANCE;
  16978. case Engine.TEXTUREFORMAT_RGB:
  16979. return this._gl.RGB;
  16980. case Engine.TEXTUREFORMAT_R:
  16981. return this._gl.R8;
  16982. case Engine.TEXTUREFORMAT_RG:
  16983. return this._gl.RG8;
  16984. case Engine.TEXTUREFORMAT_ALPHA:
  16985. return this._gl.ALPHA;
  16986. }
  16987. }
  16988. return this._gl.RGBA;
  16989. };
  16990. ;
  16991. /** @hidden */
  16992. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16993. if (type === Engine.TEXTURETYPE_FLOAT) {
  16994. return this._gl.RGBA32F;
  16995. }
  16996. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16997. return this._gl.RGBA16F;
  16998. }
  16999. return this._gl.RGBA8;
  17000. };
  17001. ;
  17002. /** @hidden */
  17003. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17004. var _this = this;
  17005. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17006. this._activeRequests.push(request);
  17007. request.onCompleteObservable.add(function (request) {
  17008. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17009. });
  17010. return request;
  17011. };
  17012. /** @hidden */
  17013. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17014. var _this = this;
  17015. return new Promise(function (resolve, reject) {
  17016. _this._loadFile(url, function (data) {
  17017. resolve(data);
  17018. }, undefined, database, useArrayBuffer, function (request, exception) {
  17019. reject(exception);
  17020. });
  17021. });
  17022. };
  17023. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17024. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17025. var onload = function (data) {
  17026. loadedFiles[index] = data;
  17027. loadedFiles._internalCount++;
  17028. if (loadedFiles._internalCount === 6) {
  17029. onfinish(loadedFiles);
  17030. }
  17031. };
  17032. var onerror = function (request, exception) {
  17033. if (onErrorCallBack && request) {
  17034. onErrorCallBack(request.status + " " + request.statusText, exception);
  17035. }
  17036. };
  17037. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17038. };
  17039. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17040. if (onError === void 0) { onError = null; }
  17041. var loadedFiles = [];
  17042. loadedFiles._internalCount = 0;
  17043. for (var index = 0; index < 6; index++) {
  17044. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17045. }
  17046. };
  17047. // Statics
  17048. /**
  17049. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17050. * @returns true if the engine can be created
  17051. * @ignorenaming
  17052. */
  17053. Engine.isSupported = function () {
  17054. try {
  17055. var tempcanvas = document.createElement("canvas");
  17056. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17057. return gl != null && !!window.WebGLRenderingContext;
  17058. }
  17059. catch (e) {
  17060. return false;
  17061. }
  17062. };
  17063. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17064. Engine.ExceptionList = [
  17065. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17066. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17067. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17068. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17069. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17070. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17071. ];
  17072. /** Gets the list of created engines */
  17073. Engine.Instances = new Array();
  17074. /**
  17075. * Hidden
  17076. */
  17077. Engine._TextureLoaders = [];
  17078. // Const statics
  17079. /** Defines that alpha blending is disabled */
  17080. Engine.ALPHA_DISABLE = 0;
  17081. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17082. Engine.ALPHA_ADD = 1;
  17083. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17084. Engine.ALPHA_COMBINE = 2;
  17085. /** Defines that alpha blending to DEST - SRC * DEST */
  17086. Engine.ALPHA_SUBTRACT = 3;
  17087. /** Defines that alpha blending to SRC * DEST */
  17088. Engine.ALPHA_MULTIPLY = 4;
  17089. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17090. Engine.ALPHA_MAXIMIZED = 5;
  17091. /** Defines that alpha blending to SRC + DEST */
  17092. Engine.ALPHA_ONEONE = 6;
  17093. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17094. Engine.ALPHA_PREMULTIPLIED = 7;
  17095. /**
  17096. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17097. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17098. */
  17099. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17100. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17101. Engine.ALPHA_INTERPOLATE = 9;
  17102. /**
  17103. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17104. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17105. */
  17106. Engine.ALPHA_SCREENMODE = 10;
  17107. /** Defines that the ressource is not delayed*/
  17108. Engine.DELAYLOADSTATE_NONE = 0;
  17109. /** Defines that the ressource was successfully delay loaded */
  17110. Engine.DELAYLOADSTATE_LOADED = 1;
  17111. /** Defines that the ressource is currently delay loading */
  17112. Engine.DELAYLOADSTATE_LOADING = 2;
  17113. /** Defines that the ressource is delayed and has not started loading */
  17114. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17115. // Depht or Stencil test Constants.
  17116. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17117. Engine.NEVER = 0x0200;
  17118. /** 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 */
  17119. Engine.ALWAYS = 0x0207;
  17120. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17121. Engine.LESS = 0x0201;
  17122. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17123. Engine.EQUAL = 0x0202;
  17124. /** 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 */
  17125. Engine.LEQUAL = 0x0203;
  17126. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17127. Engine.GREATER = 0x0204;
  17128. /** 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 */
  17129. Engine.GEQUAL = 0x0206;
  17130. /** 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 */
  17131. Engine.NOTEQUAL = 0x0205;
  17132. // Stencil Actions Constants.
  17133. /** Passed to stencilOperation to specify that stencil value must be kept */
  17134. Engine.KEEP = 0x1E00;
  17135. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17136. Engine.REPLACE = 0x1E01;
  17137. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17138. Engine.INCR = 0x1E02;
  17139. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17140. Engine.DECR = 0x1E03;
  17141. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17142. Engine.INVERT = 0x150A;
  17143. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17144. Engine.INCR_WRAP = 0x8507;
  17145. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17146. Engine.DECR_WRAP = 0x8508;
  17147. /** Texture is not repeating outside of 0..1 UVs */
  17148. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17149. /** Texture is repeating outside of 0..1 UVs */
  17150. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17151. /** Texture is repeating and mirrored */
  17152. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17153. /** ALPHA */
  17154. Engine.TEXTUREFORMAT_ALPHA = 0;
  17155. /** LUMINANCE */
  17156. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17157. /** LUMINANCE_ALPHA */
  17158. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17159. /** RGB */
  17160. Engine.TEXTUREFORMAT_RGB = 4;
  17161. /** RGBA */
  17162. Engine.TEXTUREFORMAT_RGBA = 5;
  17163. /** R */
  17164. Engine.TEXTUREFORMAT_R = 6;
  17165. /** RG */
  17166. Engine.TEXTUREFORMAT_RG = 7;
  17167. /** UNSIGNED_INT */
  17168. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17169. /** FLOAT */
  17170. Engine.TEXTURETYPE_FLOAT = 1;
  17171. /** HALF_FLOAT */
  17172. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17173. /** nearest is mag = nearest and min = nearest and mip = linear */
  17174. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17175. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17176. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17177. /** Trilinear is mag = linear and min = linear and mip = linear */
  17178. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17179. /** nearest is mag = nearest and min = nearest and mip = linear */
  17180. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17181. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17182. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17183. /** Trilinear is mag = linear and min = linear and mip = linear */
  17184. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17185. /** mag = nearest and min = nearest and mip = nearest */
  17186. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17187. /** mag = nearest and min = linear and mip = nearest */
  17188. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17189. /** mag = nearest and min = linear and mip = linear */
  17190. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17191. /** mag = nearest and min = linear and mip = none */
  17192. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17193. /** mag = nearest and min = nearest and mip = none */
  17194. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17195. /** mag = linear and min = nearest and mip = nearest */
  17196. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17197. /** mag = linear and min = nearest and mip = linear */
  17198. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17199. /** mag = linear and min = linear and mip = none */
  17200. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17201. /** mag = linear and min = nearest and mip = none */
  17202. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17203. /** Explicit coordinates mode */
  17204. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17205. /** Spherical coordinates mode */
  17206. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17207. /** Planar coordinates mode */
  17208. Engine.TEXTURE_PLANAR_MODE = 2;
  17209. /** Cubic coordinates mode */
  17210. Engine.TEXTURE_CUBIC_MODE = 3;
  17211. /** Projection coordinates mode */
  17212. Engine.TEXTURE_PROJECTION_MODE = 4;
  17213. /** Skybox coordinates mode */
  17214. Engine.TEXTURE_SKYBOX_MODE = 5;
  17215. /** Inverse Cubic coordinates mode */
  17216. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17217. /** Equirectangular coordinates mode */
  17218. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17219. /** Equirectangular Fixed coordinates mode */
  17220. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17221. /** Equirectangular Fixed Mirrored coordinates mode */
  17222. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17223. // Texture rescaling mode
  17224. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17225. Engine.SCALEMODE_FLOOR = 1;
  17226. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17227. Engine.SCALEMODE_NEAREST = 2;
  17228. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17229. Engine.SCALEMODE_CEILING = 3;
  17230. // Updatable statics so stick with vars here
  17231. /**
  17232. * Gets or sets the epsilon value used by collision engine
  17233. */
  17234. Engine.CollisionsEpsilon = 0.001;
  17235. /**
  17236. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17237. */
  17238. Engine.CodeRepository = "src/";
  17239. /**
  17240. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17241. */
  17242. Engine.ShadersRepository = "src/Shaders/";
  17243. return Engine;
  17244. }());
  17245. BABYLON.Engine = Engine;
  17246. })(BABYLON || (BABYLON = {}));
  17247. //# sourceMappingURL=babylon.engine.js.map
  17248. var BABYLON;
  17249. (function (BABYLON) {
  17250. /**
  17251. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17252. */
  17253. var Node = /** @class */ (function () {
  17254. /**
  17255. * Creates a new Node
  17256. * @param {string} name - the name and id to be given to this node
  17257. * @param {BABYLON.Scene} the scene this node will be added to
  17258. */
  17259. function Node(name, scene) {
  17260. if (scene === void 0) { scene = null; }
  17261. /**
  17262. * Gets or sets a string used to store user defined state for the node
  17263. */
  17264. this.state = "";
  17265. /**
  17266. * Gets or sets an object used to store user defined information for the node
  17267. */
  17268. this.metadata = null;
  17269. /**
  17270. * Gets or sets a boolean used to define if the node must be serialized
  17271. */
  17272. this.doNotSerialize = false;
  17273. /** @hidden */
  17274. this._isDisposed = false;
  17275. /**
  17276. * Gets a list of Animations associated with the node
  17277. */
  17278. this.animations = new Array();
  17279. this._ranges = {};
  17280. this._isEnabled = true;
  17281. this._isReady = true;
  17282. /** @hidden */
  17283. this._currentRenderId = -1;
  17284. this._parentRenderId = -1;
  17285. this._childRenderId = -1;
  17286. this._animationPropertiesOverride = null;
  17287. /**
  17288. * An event triggered when the mesh is disposed
  17289. */
  17290. this.onDisposeObservable = new BABYLON.Observable();
  17291. // Behaviors
  17292. this._behaviors = new Array();
  17293. this.name = name;
  17294. this.id = name;
  17295. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17296. this.uniqueId = this._scene.getUniqueId();
  17297. this._initCache();
  17298. }
  17299. /**
  17300. * Add a new node constructor
  17301. * @param type defines the type name of the node to construct
  17302. * @param constructorFunc defines the constructor function
  17303. */
  17304. Node.AddNodeConstructor = function (type, constructorFunc) {
  17305. this._NodeConstructors[type] = constructorFunc;
  17306. };
  17307. /**
  17308. * Returns a node constructor based on type name
  17309. * @param type defines the type name
  17310. * @param name defines the new node name
  17311. * @param scene defines the hosting scene
  17312. * @param options defines optional options to transmit to constructors
  17313. * @returns the new constructor or null
  17314. */
  17315. Node.Construct = function (type, name, scene, options) {
  17316. var constructorFunc = this._NodeConstructors[type];
  17317. if (!constructorFunc) {
  17318. return null;
  17319. }
  17320. return constructorFunc(name, scene, options);
  17321. };
  17322. /**
  17323. * Gets a boolean indicating if the node has been disposed
  17324. * @returns true if the node was disposed
  17325. */
  17326. Node.prototype.isDisposed = function () {
  17327. return this._isDisposed;
  17328. };
  17329. Object.defineProperty(Node.prototype, "parent", {
  17330. get: function () {
  17331. return this._parentNode;
  17332. },
  17333. /**
  17334. * Gets or sets the parent of the node
  17335. */
  17336. set: function (parent) {
  17337. if (this._parentNode === parent) {
  17338. return;
  17339. }
  17340. // Remove self from list of children of parent
  17341. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17342. var index = this._parentNode._children.indexOf(this);
  17343. if (index !== -1) {
  17344. this._parentNode._children.splice(index, 1);
  17345. }
  17346. }
  17347. // Store new parent
  17348. this._parentNode = parent;
  17349. // Add as child to new parent
  17350. if (this._parentNode) {
  17351. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17352. this._parentNode._children = new Array();
  17353. }
  17354. this._parentNode._children.push(this);
  17355. }
  17356. },
  17357. enumerable: true,
  17358. configurable: true
  17359. });
  17360. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17361. /**
  17362. * Gets or sets the animation properties override
  17363. */
  17364. get: function () {
  17365. if (!this._animationPropertiesOverride) {
  17366. return this._scene.animationPropertiesOverride;
  17367. }
  17368. return this._animationPropertiesOverride;
  17369. },
  17370. set: function (value) {
  17371. this._animationPropertiesOverride = value;
  17372. },
  17373. enumerable: true,
  17374. configurable: true
  17375. });
  17376. /**
  17377. * Gets a string idenfifying the name of the class
  17378. * @returns "Node" string
  17379. */
  17380. Node.prototype.getClassName = function () {
  17381. return "Node";
  17382. };
  17383. Object.defineProperty(Node.prototype, "onDispose", {
  17384. /**
  17385. * Sets a callback that will be raised when the node will be disposed
  17386. */
  17387. set: function (callback) {
  17388. if (this._onDisposeObserver) {
  17389. this.onDisposeObservable.remove(this._onDisposeObserver);
  17390. }
  17391. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17392. },
  17393. enumerable: true,
  17394. configurable: true
  17395. });
  17396. /**
  17397. * Gets the scene of the node
  17398. * @returns a {BABYLON.Scene}
  17399. */
  17400. Node.prototype.getScene = function () {
  17401. return this._scene;
  17402. };
  17403. /**
  17404. * Gets the engine of the node
  17405. * @returns a {BABYLON.Engine}
  17406. */
  17407. Node.prototype.getEngine = function () {
  17408. return this._scene.getEngine();
  17409. };
  17410. /**
  17411. * Attach a behavior to the node
  17412. * @see http://doc.babylonjs.com/features/behaviour
  17413. * @param behavior defines the behavior to attach
  17414. * @returns the current Node
  17415. */
  17416. Node.prototype.addBehavior = function (behavior) {
  17417. var _this = this;
  17418. var index = this._behaviors.indexOf(behavior);
  17419. if (index !== -1) {
  17420. return this;
  17421. }
  17422. behavior.init();
  17423. if (this._scene.isLoading) {
  17424. // We defer the attach when the scene will be loaded
  17425. this._scene.onDataLoadedObservable.addOnce(function () {
  17426. behavior.attach(_this);
  17427. });
  17428. }
  17429. else {
  17430. behavior.attach(this);
  17431. }
  17432. this._behaviors.push(behavior);
  17433. return this;
  17434. };
  17435. /**
  17436. * Remove an attached behavior
  17437. * @see http://doc.babylonjs.com/features/behaviour
  17438. * @param behavior defines the behavior to attach
  17439. * @returns the current Node
  17440. */
  17441. Node.prototype.removeBehavior = function (behavior) {
  17442. var index = this._behaviors.indexOf(behavior);
  17443. if (index === -1) {
  17444. return this;
  17445. }
  17446. this._behaviors[index].detach();
  17447. this._behaviors.splice(index, 1);
  17448. return this;
  17449. };
  17450. Object.defineProperty(Node.prototype, "behaviors", {
  17451. /**
  17452. * Gets the list of attached behaviors
  17453. * @see http://doc.babylonjs.com/features/behaviour
  17454. */
  17455. get: function () {
  17456. return this._behaviors;
  17457. },
  17458. enumerable: true,
  17459. configurable: true
  17460. });
  17461. /**
  17462. * Gets an attached behavior by name
  17463. * @param name defines the name of the behavior to look for
  17464. * @see http://doc.babylonjs.com/features/behaviour
  17465. * @returns null if behavior was not found else the requested behavior
  17466. */
  17467. Node.prototype.getBehaviorByName = function (name) {
  17468. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17469. var behavior = _a[_i];
  17470. if (behavior.name === name) {
  17471. return behavior;
  17472. }
  17473. }
  17474. return null;
  17475. };
  17476. /**
  17477. * Returns the world matrix of the node
  17478. * @returns a matrix containing the node's world matrix
  17479. */
  17480. Node.prototype.getWorldMatrix = function () {
  17481. return BABYLON.Matrix.Identity();
  17482. };
  17483. /** @hidden */
  17484. Node.prototype._getWorldMatrixDeterminant = function () {
  17485. return 1;
  17486. };
  17487. // override it in derived class if you add new variables to the cache
  17488. // and call the parent class method
  17489. /** @hidden */
  17490. Node.prototype._initCache = function () {
  17491. this._cache = {};
  17492. this._cache.parent = undefined;
  17493. };
  17494. /** @hidden */
  17495. Node.prototype.updateCache = function (force) {
  17496. if (!force && this.isSynchronized())
  17497. return;
  17498. this._cache.parent = this.parent;
  17499. this._updateCache();
  17500. };
  17501. // override it in derived class if you add new variables to the cache
  17502. // and call the parent class method if !ignoreParentClass
  17503. /** @hidden */
  17504. Node.prototype._updateCache = function (ignoreParentClass) {
  17505. };
  17506. // override it in derived class if you add new variables to the cache
  17507. /** @hidden */
  17508. Node.prototype._isSynchronized = function () {
  17509. return true;
  17510. };
  17511. /** @hidden */
  17512. Node.prototype._markSyncedWithParent = function () {
  17513. if (this.parent) {
  17514. this._parentRenderId = this.parent._childRenderId;
  17515. }
  17516. };
  17517. /** @hidden */
  17518. Node.prototype.isSynchronizedWithParent = function () {
  17519. if (!this.parent) {
  17520. return true;
  17521. }
  17522. if (this._parentRenderId !== this.parent._childRenderId) {
  17523. return false;
  17524. }
  17525. return this.parent.isSynchronized();
  17526. };
  17527. /** @hidden */
  17528. Node.prototype.isSynchronized = function (updateCache) {
  17529. var check = this.hasNewParent();
  17530. check = check || !this.isSynchronizedWithParent();
  17531. check = check || !this._isSynchronized();
  17532. if (updateCache)
  17533. this.updateCache(true);
  17534. return !check;
  17535. };
  17536. /** @hidden */
  17537. Node.prototype.hasNewParent = function (update) {
  17538. if (this._cache.parent === this.parent)
  17539. return false;
  17540. if (update)
  17541. this._cache.parent = this.parent;
  17542. return true;
  17543. };
  17544. /**
  17545. * Is this node ready to be used/rendered
  17546. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17547. * @return true if the node is ready
  17548. */
  17549. Node.prototype.isReady = function (completeCheck) {
  17550. if (completeCheck === void 0) { completeCheck = false; }
  17551. return this._isReady;
  17552. };
  17553. /**
  17554. * Is this node enabled?
  17555. * 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
  17556. * @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
  17557. * @return whether this node (and its parent) is enabled
  17558. */
  17559. Node.prototype.isEnabled = function (checkAncestors) {
  17560. if (checkAncestors === void 0) { checkAncestors = true; }
  17561. if (checkAncestors === false) {
  17562. return this._isEnabled;
  17563. }
  17564. if (this._isEnabled === false) {
  17565. return false;
  17566. }
  17567. if (this.parent !== undefined && this.parent !== null) {
  17568. return this.parent.isEnabled(checkAncestors);
  17569. }
  17570. return true;
  17571. };
  17572. /**
  17573. * Set the enabled state of this node
  17574. * @param value defines the new enabled state
  17575. */
  17576. Node.prototype.setEnabled = function (value) {
  17577. this._isEnabled = value;
  17578. };
  17579. /**
  17580. * Is this node a descendant of the given node?
  17581. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17582. * @param ancestor defines the parent node to inspect
  17583. * @returns a boolean indicating if this node is a descendant of the given node
  17584. */
  17585. Node.prototype.isDescendantOf = function (ancestor) {
  17586. if (this.parent) {
  17587. if (this.parent === ancestor) {
  17588. return true;
  17589. }
  17590. return this.parent.isDescendantOf(ancestor);
  17591. }
  17592. return false;
  17593. };
  17594. /** @hidden */
  17595. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17596. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17597. if (!this._children) {
  17598. return;
  17599. }
  17600. for (var index = 0; index < this._children.length; index++) {
  17601. var item = this._children[index];
  17602. if (!predicate || predicate(item)) {
  17603. results.push(item);
  17604. }
  17605. if (!directDescendantsOnly) {
  17606. item._getDescendants(results, false, predicate);
  17607. }
  17608. }
  17609. };
  17610. /**
  17611. * Will return all nodes that have this node as ascendant
  17612. * @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
  17613. * @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
  17614. * @return all children nodes of all types
  17615. */
  17616. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17617. var results = new Array();
  17618. this._getDescendants(results, directDescendantsOnly, predicate);
  17619. return results;
  17620. };
  17621. /**
  17622. * Get all child-meshes of this node
  17623. * @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
  17624. * @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
  17625. * @returns an array of {BABYLON.AbstractMesh}
  17626. */
  17627. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17628. var results = [];
  17629. this._getDescendants(results, directDescendantsOnly, function (node) {
  17630. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17631. });
  17632. return results;
  17633. };
  17634. /**
  17635. * Get all child-transformNodes of this node
  17636. * @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
  17637. * @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
  17638. * @returns an array of {BABYLON.TransformNode}
  17639. */
  17640. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17641. var results = [];
  17642. this._getDescendants(results, directDescendantsOnly, function (node) {
  17643. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17644. });
  17645. return results;
  17646. };
  17647. /**
  17648. * Get all direct children of this node
  17649. * @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
  17650. * @returns an array of {BABYLON.Node}
  17651. */
  17652. Node.prototype.getChildren = function (predicate) {
  17653. return this.getDescendants(true, predicate);
  17654. };
  17655. /** @hidden */
  17656. Node.prototype._setReady = function (state) {
  17657. if (state === this._isReady) {
  17658. return;
  17659. }
  17660. if (!state) {
  17661. this._isReady = false;
  17662. return;
  17663. }
  17664. if (this.onReady) {
  17665. this.onReady(this);
  17666. }
  17667. this._isReady = true;
  17668. };
  17669. /**
  17670. * Get an animation by name
  17671. * @param name defines the name of the animation to look for
  17672. * @returns null if not found else the requested animation
  17673. */
  17674. Node.prototype.getAnimationByName = function (name) {
  17675. for (var i = 0; i < this.animations.length; i++) {
  17676. var animation = this.animations[i];
  17677. if (animation.name === name) {
  17678. return animation;
  17679. }
  17680. }
  17681. return null;
  17682. };
  17683. /**
  17684. * Creates an animation range for this node
  17685. * @param name defines the name of the range
  17686. * @param from defines the starting key
  17687. * @param to defines the end key
  17688. */
  17689. Node.prototype.createAnimationRange = function (name, from, to) {
  17690. // check name not already in use
  17691. if (!this._ranges[name]) {
  17692. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17693. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17694. if (this.animations[i]) {
  17695. this.animations[i].createRange(name, from, to);
  17696. }
  17697. }
  17698. }
  17699. };
  17700. /**
  17701. * Delete a specific animation range
  17702. * @param name defines the name of the range to delete
  17703. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17704. */
  17705. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17706. if (deleteFrames === void 0) { deleteFrames = true; }
  17707. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17708. if (this.animations[i]) {
  17709. this.animations[i].deleteRange(name, deleteFrames);
  17710. }
  17711. }
  17712. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17713. };
  17714. /**
  17715. * Get an animation range by name
  17716. * @param name defines the name of the animation range to look for
  17717. * @returns null if not found else the requested animation range
  17718. */
  17719. Node.prototype.getAnimationRange = function (name) {
  17720. return this._ranges[name];
  17721. };
  17722. /**
  17723. * Will start the animation sequence
  17724. * @param name defines the range frames for animation sequence
  17725. * @param loop defines if the animation should loop (false by default)
  17726. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17727. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17728. * @returns the object created for this animation. If range does not exist, it will return null
  17729. */
  17730. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17731. var range = this.getAnimationRange(name);
  17732. if (!range) {
  17733. return null;
  17734. }
  17735. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17736. };
  17737. /**
  17738. * Serialize animation ranges into a JSON compatible object
  17739. * @returns serialization object
  17740. */
  17741. Node.prototype.serializeAnimationRanges = function () {
  17742. var serializationRanges = [];
  17743. for (var name in this._ranges) {
  17744. var localRange = this._ranges[name];
  17745. if (!localRange) {
  17746. continue;
  17747. }
  17748. var range = {};
  17749. range.name = name;
  17750. range.from = localRange.from;
  17751. range.to = localRange.to;
  17752. serializationRanges.push(range);
  17753. }
  17754. return serializationRanges;
  17755. };
  17756. /**
  17757. * Computes the world matrix of the node
  17758. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17759. * @returns the world matrix
  17760. */
  17761. Node.prototype.computeWorldMatrix = function (force) {
  17762. return BABYLON.Matrix.Identity();
  17763. };
  17764. /**
  17765. * Releases resources associated with this node.
  17766. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17767. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17768. */
  17769. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17770. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17771. if (!doNotRecurse) {
  17772. var nodes = this.getDescendants(true);
  17773. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17774. var node = nodes_1[_i];
  17775. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17776. }
  17777. }
  17778. else {
  17779. var transformNodes = this.getChildTransformNodes(true);
  17780. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17781. var transformNode = transformNodes_1[_a];
  17782. transformNode.parent = null;
  17783. transformNode.computeWorldMatrix(true);
  17784. }
  17785. }
  17786. this.parent = null;
  17787. // Callback
  17788. this.onDisposeObservable.notifyObservers(this);
  17789. this.onDisposeObservable.clear();
  17790. // Behaviors
  17791. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17792. var behavior = _c[_b];
  17793. behavior.detach();
  17794. }
  17795. this._behaviors = [];
  17796. this._isDisposed = true;
  17797. };
  17798. /**
  17799. * Parse animation range data from a serialization object and store them into a given node
  17800. * @param node defines where to store the animation ranges
  17801. * @param parsedNode defines the serialization object to read data from
  17802. * @param scene defines the hosting scene
  17803. */
  17804. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17805. if (parsedNode.ranges) {
  17806. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17807. var data = parsedNode.ranges[index];
  17808. node.createAnimationRange(data.name, data.from, data.to);
  17809. }
  17810. }
  17811. };
  17812. Node._NodeConstructors = {};
  17813. __decorate([
  17814. BABYLON.serialize()
  17815. ], Node.prototype, "name", void 0);
  17816. __decorate([
  17817. BABYLON.serialize()
  17818. ], Node.prototype, "id", void 0);
  17819. __decorate([
  17820. BABYLON.serialize()
  17821. ], Node.prototype, "uniqueId", void 0);
  17822. __decorate([
  17823. BABYLON.serialize()
  17824. ], Node.prototype, "state", void 0);
  17825. __decorate([
  17826. BABYLON.serialize()
  17827. ], Node.prototype, "metadata", void 0);
  17828. return Node;
  17829. }());
  17830. BABYLON.Node = Node;
  17831. })(BABYLON || (BABYLON = {}));
  17832. //# sourceMappingURL=babylon.node.js.map
  17833. var BABYLON;
  17834. (function (BABYLON) {
  17835. var BoundingSphere = /** @class */ (function () {
  17836. /**
  17837. * Creates a new bounding sphere
  17838. * @param min defines the minimum vector (in local space)
  17839. * @param max defines the maximum vector (in local space)
  17840. */
  17841. function BoundingSphere(min, max) {
  17842. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17843. this.reConstruct(min, max);
  17844. }
  17845. /**
  17846. * Recreates the entire bounding sphere from scratch
  17847. * @param min defines the new minimum vector (in local space)
  17848. * @param max defines the new maximum vector (in local space)
  17849. */
  17850. BoundingSphere.prototype.reConstruct = function (min, max) {
  17851. this.minimum = min.clone();
  17852. this.maximum = max.clone();
  17853. var distance = BABYLON.Vector3.Distance(min, max);
  17854. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17855. this.radius = distance * 0.5;
  17856. this.centerWorld = BABYLON.Vector3.Zero();
  17857. this._update(BABYLON.Matrix.Identity());
  17858. };
  17859. /**
  17860. * Scale the current bounding sphere by applying a scale factor
  17861. * @param factor defines the scale factor to apply
  17862. * @returns the current bounding box
  17863. */
  17864. BoundingSphere.prototype.scale = function (factor) {
  17865. var newRadius = this.radius * factor;
  17866. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17867. var min = this.center.subtract(newRadiusVector);
  17868. var max = this.center.add(newRadiusVector);
  17869. this.reConstruct(min, max);
  17870. return this;
  17871. };
  17872. // Methods
  17873. BoundingSphere.prototype._update = function (world) {
  17874. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17875. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17876. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17877. };
  17878. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17879. for (var i = 0; i < 6; i++) {
  17880. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17881. return false;
  17882. }
  17883. return true;
  17884. };
  17885. BoundingSphere.prototype.intersectsPoint = function (point) {
  17886. var x = this.centerWorld.x - point.x;
  17887. var y = this.centerWorld.y - point.y;
  17888. var z = this.centerWorld.z - point.z;
  17889. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17890. if (this.radiusWorld < distance)
  17891. return false;
  17892. return true;
  17893. };
  17894. // Statics
  17895. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17896. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17897. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17898. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17899. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17900. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17901. return false;
  17902. return true;
  17903. };
  17904. return BoundingSphere;
  17905. }());
  17906. BABYLON.BoundingSphere = BoundingSphere;
  17907. })(BABYLON || (BABYLON = {}));
  17908. //# sourceMappingURL=babylon.boundingSphere.js.map
  17909. var BABYLON;
  17910. (function (BABYLON) {
  17911. var BoundingBox = /** @class */ (function () {
  17912. /**
  17913. * Creates a new bounding box
  17914. * @param min defines the minimum vector (in local space)
  17915. * @param max defines the maximum vector (in local space)
  17916. */
  17917. function BoundingBox(min, max) {
  17918. this.vectorsWorld = new Array();
  17919. this.reConstruct(min, max);
  17920. }
  17921. // Methods
  17922. /**
  17923. * Recreates the entire bounding box from scratch
  17924. * @param min defines the new minimum vector (in local space)
  17925. * @param max defines the new maximum vector (in local space)
  17926. */
  17927. BoundingBox.prototype.reConstruct = function (min, max) {
  17928. this.minimum = min.clone();
  17929. this.maximum = max.clone();
  17930. // Bounding vectors
  17931. this.vectors = new Array();
  17932. this.vectors.push(this.minimum.clone());
  17933. this.vectors.push(this.maximum.clone());
  17934. this.vectors.push(this.minimum.clone());
  17935. this.vectors[2].x = this.maximum.x;
  17936. this.vectors.push(this.minimum.clone());
  17937. this.vectors[3].y = this.maximum.y;
  17938. this.vectors.push(this.minimum.clone());
  17939. this.vectors[4].z = this.maximum.z;
  17940. this.vectors.push(this.maximum.clone());
  17941. this.vectors[5].z = this.minimum.z;
  17942. this.vectors.push(this.maximum.clone());
  17943. this.vectors[6].x = this.minimum.x;
  17944. this.vectors.push(this.maximum.clone());
  17945. this.vectors[7].y = this.minimum.y;
  17946. // OBB
  17947. this.center = this.maximum.add(this.minimum).scale(0.5);
  17948. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17949. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17950. // World
  17951. for (var index = 0; index < this.vectors.length; index++) {
  17952. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17953. }
  17954. this.minimumWorld = BABYLON.Vector3.Zero();
  17955. this.maximumWorld = BABYLON.Vector3.Zero();
  17956. this.centerWorld = BABYLON.Vector3.Zero();
  17957. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17958. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17959. };
  17960. /**
  17961. * Scale the current bounding box by applying a scale factor
  17962. * @param factor defines the scale factor to apply
  17963. * @returns the current bounding box
  17964. */
  17965. BoundingBox.prototype.scale = function (factor) {
  17966. var diff = this.maximum.subtract(this.minimum);
  17967. var distance = diff.length() * factor;
  17968. diff.normalize();
  17969. var newRadius = diff.scale(distance / 2);
  17970. var min = this.center.subtract(newRadius);
  17971. var max = this.center.add(newRadius);
  17972. this.reConstruct(min, max);
  17973. return this;
  17974. };
  17975. BoundingBox.prototype.getWorldMatrix = function () {
  17976. return this._worldMatrix;
  17977. };
  17978. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17979. this._worldMatrix.copyFrom(matrix);
  17980. return this;
  17981. };
  17982. BoundingBox.prototype._update = function (world) {
  17983. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17984. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17985. for (var index = 0; index < this.vectors.length; index++) {
  17986. var v = this.vectorsWorld[index];
  17987. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17988. if (v.x < this.minimumWorld.x)
  17989. this.minimumWorld.x = v.x;
  17990. if (v.y < this.minimumWorld.y)
  17991. this.minimumWorld.y = v.y;
  17992. if (v.z < this.minimumWorld.z)
  17993. this.minimumWorld.z = v.z;
  17994. if (v.x > this.maximumWorld.x)
  17995. this.maximumWorld.x = v.x;
  17996. if (v.y > this.maximumWorld.y)
  17997. this.maximumWorld.y = v.y;
  17998. if (v.z > this.maximumWorld.z)
  17999. this.maximumWorld.z = v.z;
  18000. }
  18001. // Extend
  18002. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18003. this.extendSizeWorld.scaleInPlace(0.5);
  18004. // OBB
  18005. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18006. this.centerWorld.scaleInPlace(0.5);
  18007. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18008. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18009. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18010. this._worldMatrix = world;
  18011. };
  18012. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18013. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18014. };
  18015. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18016. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18017. };
  18018. BoundingBox.prototype.intersectsPoint = function (point) {
  18019. var delta = -BABYLON.Epsilon;
  18020. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18021. return false;
  18022. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18023. return false;
  18024. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18025. return false;
  18026. return true;
  18027. };
  18028. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18029. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18030. };
  18031. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18032. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18033. return false;
  18034. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18035. return false;
  18036. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18037. return false;
  18038. return true;
  18039. };
  18040. // Statics
  18041. BoundingBox.Intersects = function (box0, box1) {
  18042. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18043. return false;
  18044. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18045. return false;
  18046. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18047. return false;
  18048. return true;
  18049. };
  18050. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18051. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18052. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18053. return (num <= (sphereRadius * sphereRadius));
  18054. };
  18055. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18056. for (var p = 0; p < 6; p++) {
  18057. for (var i = 0; i < 8; i++) {
  18058. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18059. return false;
  18060. }
  18061. }
  18062. }
  18063. return true;
  18064. };
  18065. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18066. for (var p = 0; p < 6; p++) {
  18067. var inCount = 8;
  18068. for (var i = 0; i < 8; i++) {
  18069. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18070. --inCount;
  18071. }
  18072. else {
  18073. break;
  18074. }
  18075. }
  18076. if (inCount === 0)
  18077. return false;
  18078. }
  18079. return true;
  18080. };
  18081. return BoundingBox;
  18082. }());
  18083. BABYLON.BoundingBox = BoundingBox;
  18084. })(BABYLON || (BABYLON = {}));
  18085. //# sourceMappingURL=babylon.boundingBox.js.map
  18086. var BABYLON;
  18087. (function (BABYLON) {
  18088. var computeBoxExtents = function (axis, box) {
  18089. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18090. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18091. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18092. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18093. var r = r0 + r1 + r2;
  18094. return {
  18095. min: p - r,
  18096. max: p + r
  18097. };
  18098. };
  18099. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18100. var axisOverlap = function (axis, box0, box1) {
  18101. var result0 = computeBoxExtents(axis, box0);
  18102. var result1 = computeBoxExtents(axis, box1);
  18103. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18104. };
  18105. var BoundingInfo = /** @class */ (function () {
  18106. function BoundingInfo(minimum, maximum) {
  18107. this.minimum = minimum;
  18108. this.maximum = maximum;
  18109. this._isLocked = false;
  18110. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18111. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18112. }
  18113. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18114. get: function () {
  18115. return this._isLocked;
  18116. },
  18117. set: function (value) {
  18118. this._isLocked = value;
  18119. },
  18120. enumerable: true,
  18121. configurable: true
  18122. });
  18123. // Methods
  18124. BoundingInfo.prototype.update = function (world) {
  18125. if (this._isLocked) {
  18126. return;
  18127. }
  18128. this.boundingBox._update(world);
  18129. this.boundingSphere._update(world);
  18130. };
  18131. /**
  18132. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18133. * @param center New center of the bounding info
  18134. * @param extend New extend of the bounding info
  18135. */
  18136. BoundingInfo.prototype.centerOn = function (center, extend) {
  18137. this.minimum = center.subtract(extend);
  18138. this.maximum = center.add(extend);
  18139. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18140. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18141. return this;
  18142. };
  18143. /**
  18144. * Scale the current bounding info by applying a scale factor
  18145. * @param factor defines the scale factor to apply
  18146. * @returns the current bounding info
  18147. */
  18148. BoundingInfo.prototype.scale = function (factor) {
  18149. this.boundingBox.scale(factor);
  18150. this.boundingSphere.scale(factor);
  18151. return this;
  18152. };
  18153. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18154. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18155. return false;
  18156. return this.boundingBox.isInFrustum(frustumPlanes);
  18157. };
  18158. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18159. /**
  18160. * Gets the world distance between the min and max points of the bounding box
  18161. */
  18162. get: function () {
  18163. var boundingBox = this.boundingBox;
  18164. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18165. return size.length();
  18166. },
  18167. enumerable: true,
  18168. configurable: true
  18169. });
  18170. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18171. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18172. };
  18173. BoundingInfo.prototype._checkCollision = function (collider) {
  18174. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18175. };
  18176. BoundingInfo.prototype.intersectsPoint = function (point) {
  18177. if (!this.boundingSphere.centerWorld) {
  18178. return false;
  18179. }
  18180. if (!this.boundingSphere.intersectsPoint(point)) {
  18181. return false;
  18182. }
  18183. if (!this.boundingBox.intersectsPoint(point)) {
  18184. return false;
  18185. }
  18186. return true;
  18187. };
  18188. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18189. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18190. return false;
  18191. }
  18192. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18193. return false;
  18194. }
  18195. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18196. return false;
  18197. }
  18198. if (!precise) {
  18199. return true;
  18200. }
  18201. var box0 = this.boundingBox;
  18202. var box1 = boundingInfo.boundingBox;
  18203. if (!axisOverlap(box0.directions[0], box0, box1))
  18204. return false;
  18205. if (!axisOverlap(box0.directions[1], box0, box1))
  18206. return false;
  18207. if (!axisOverlap(box0.directions[2], box0, box1))
  18208. return false;
  18209. if (!axisOverlap(box1.directions[0], box0, box1))
  18210. return false;
  18211. if (!axisOverlap(box1.directions[1], box0, box1))
  18212. return false;
  18213. if (!axisOverlap(box1.directions[2], box0, box1))
  18214. return false;
  18215. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18216. return false;
  18217. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18218. return false;
  18219. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18220. return false;
  18221. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18222. return false;
  18223. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18224. return false;
  18225. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18226. return false;
  18227. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18228. return false;
  18229. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18230. return false;
  18231. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18232. return false;
  18233. return true;
  18234. };
  18235. return BoundingInfo;
  18236. }());
  18237. BABYLON.BoundingInfo = BoundingInfo;
  18238. })(BABYLON || (BABYLON = {}));
  18239. //# sourceMappingURL=babylon.boundingInfo.js.map
  18240. var BABYLON;
  18241. (function (BABYLON) {
  18242. var TransformNode = /** @class */ (function (_super) {
  18243. __extends(TransformNode, _super);
  18244. function TransformNode(name, scene, isPure) {
  18245. if (scene === void 0) { scene = null; }
  18246. if (isPure === void 0) { isPure = true; }
  18247. var _this = _super.call(this, name, scene) || this;
  18248. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18249. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18250. _this._up = new BABYLON.Vector3(0, 1, 0);
  18251. _this._right = new BABYLON.Vector3(1, 0, 0);
  18252. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18253. // Properties
  18254. _this._rotation = BABYLON.Vector3.Zero();
  18255. _this._scaling = BABYLON.Vector3.One();
  18256. _this._isDirty = false;
  18257. /**
  18258. * Set the billboard mode. Default is 0.
  18259. *
  18260. * | Value | Type | Description |
  18261. * | --- | --- | --- |
  18262. * | 0 | BILLBOARDMODE_NONE | |
  18263. * | 1 | BILLBOARDMODE_X | |
  18264. * | 2 | BILLBOARDMODE_Y | |
  18265. * | 4 | BILLBOARDMODE_Z | |
  18266. * | 7 | BILLBOARDMODE_ALL | |
  18267. *
  18268. */
  18269. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18270. _this.scalingDeterminant = 1;
  18271. _this.infiniteDistance = false;
  18272. /**
  18273. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18274. * By default the system will update normals to compensate
  18275. */
  18276. _this.ignoreNonUniformScaling = false;
  18277. _this.position = BABYLON.Vector3.Zero();
  18278. _this._localWorld = BABYLON.Matrix.Zero();
  18279. _this._worldMatrix = BABYLON.Matrix.Zero();
  18280. _this._worldMatrixDeterminant = 0;
  18281. _this._absolutePosition = BABYLON.Vector3.Zero();
  18282. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18283. _this._postMultiplyPivotMatrix = false;
  18284. _this._isWorldMatrixFrozen = false;
  18285. /**
  18286. * An event triggered after the world matrix is updated
  18287. */
  18288. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18289. _this._nonUniformScaling = false;
  18290. if (isPure) {
  18291. _this.getScene().addTransformNode(_this);
  18292. }
  18293. return _this;
  18294. }
  18295. /**
  18296. * Gets a string identifying the name of the class
  18297. * @returns "TransformNode" string
  18298. */
  18299. TransformNode.prototype.getClassName = function () {
  18300. return "TransformNode";
  18301. };
  18302. Object.defineProperty(TransformNode.prototype, "rotation", {
  18303. /**
  18304. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18305. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18306. * Default : (0.0, 0.0, 0.0)
  18307. */
  18308. get: function () {
  18309. return this._rotation;
  18310. },
  18311. set: function (newRotation) {
  18312. this._rotation = newRotation;
  18313. },
  18314. enumerable: true,
  18315. configurable: true
  18316. });
  18317. Object.defineProperty(TransformNode.prototype, "scaling", {
  18318. /**
  18319. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18320. * Default : (1.0, 1.0, 1.0)
  18321. */
  18322. get: function () {
  18323. return this._scaling;
  18324. },
  18325. /**
  18326. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18327. * Default : (1.0, 1.0, 1.0)
  18328. */
  18329. set: function (newScaling) {
  18330. this._scaling = newScaling;
  18331. },
  18332. enumerable: true,
  18333. configurable: true
  18334. });
  18335. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18336. /**
  18337. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18338. * It's null by default.
  18339. * 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)
  18340. */
  18341. get: function () {
  18342. return this._rotationQuaternion;
  18343. },
  18344. set: function (quaternion) {
  18345. this._rotationQuaternion = quaternion;
  18346. //reset the rotation vector.
  18347. if (quaternion && this.rotation.length()) {
  18348. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18349. }
  18350. },
  18351. enumerable: true,
  18352. configurable: true
  18353. });
  18354. Object.defineProperty(TransformNode.prototype, "forward", {
  18355. /**
  18356. * The forward direction of that transform in world space.
  18357. */
  18358. get: function () {
  18359. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18360. },
  18361. enumerable: true,
  18362. configurable: true
  18363. });
  18364. Object.defineProperty(TransformNode.prototype, "up", {
  18365. /**
  18366. * The up direction of that transform in world space.
  18367. */
  18368. get: function () {
  18369. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18370. },
  18371. enumerable: true,
  18372. configurable: true
  18373. });
  18374. Object.defineProperty(TransformNode.prototype, "right", {
  18375. /**
  18376. * The right direction of that transform in world space.
  18377. */
  18378. get: function () {
  18379. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. /**
  18385. * Returns the latest update of the World matrix
  18386. * Returns a Matrix.
  18387. */
  18388. TransformNode.prototype.getWorldMatrix = function () {
  18389. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18390. this.computeWorldMatrix();
  18391. }
  18392. return this._worldMatrix;
  18393. };
  18394. /** @hidden */
  18395. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18396. return this._worldMatrixDeterminant;
  18397. };
  18398. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18399. /**
  18400. * Returns directly the latest state of the mesh World matrix.
  18401. * A Matrix is returned.
  18402. */
  18403. get: function () {
  18404. return this._worldMatrix;
  18405. },
  18406. enumerable: true,
  18407. configurable: true
  18408. });
  18409. /**
  18410. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18411. * Returns the TransformNode.
  18412. */
  18413. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18414. this._poseMatrix.copyFrom(matrix);
  18415. return this;
  18416. };
  18417. /**
  18418. * Returns the mesh Pose matrix.
  18419. * Returned object : Matrix
  18420. */
  18421. TransformNode.prototype.getPoseMatrix = function () {
  18422. return this._poseMatrix;
  18423. };
  18424. TransformNode.prototype._isSynchronized = function () {
  18425. if (this._isDirty) {
  18426. return false;
  18427. }
  18428. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18429. return false;
  18430. if (this._cache.pivotMatrixUpdated) {
  18431. return false;
  18432. }
  18433. if (this.infiniteDistance) {
  18434. return false;
  18435. }
  18436. if (!this._cache.position.equals(this.position))
  18437. return false;
  18438. if (this.rotationQuaternion) {
  18439. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18440. return false;
  18441. }
  18442. if (!this._cache.rotation.equals(this.rotation))
  18443. return false;
  18444. if (!this._cache.scaling.equals(this.scaling))
  18445. return false;
  18446. return true;
  18447. };
  18448. TransformNode.prototype._initCache = function () {
  18449. _super.prototype._initCache.call(this);
  18450. this._cache.localMatrixUpdated = false;
  18451. this._cache.position = BABYLON.Vector3.Zero();
  18452. this._cache.scaling = BABYLON.Vector3.Zero();
  18453. this._cache.rotation = BABYLON.Vector3.Zero();
  18454. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18455. this._cache.billboardMode = -1;
  18456. };
  18457. TransformNode.prototype.markAsDirty = function (property) {
  18458. if (property === "rotation") {
  18459. this.rotationQuaternion = null;
  18460. }
  18461. this._currentRenderId = Number.MAX_VALUE;
  18462. this._isDirty = true;
  18463. return this;
  18464. };
  18465. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18466. /**
  18467. * Returns the current mesh absolute position.
  18468. * Returns a Vector3.
  18469. */
  18470. get: function () {
  18471. return this._absolutePosition;
  18472. },
  18473. enumerable: true,
  18474. configurable: true
  18475. });
  18476. /**
  18477. * Sets a new matrix to apply before all other transformation
  18478. * @param matrix defines the transform matrix
  18479. * @returns the current TransformNode
  18480. */
  18481. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18482. return this.setPivotMatrix(matrix, false);
  18483. };
  18484. /**
  18485. * Sets a new pivot matrix to the current node
  18486. * @param matrix defines the new pivot matrix to use
  18487. * @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
  18488. * @returns the current TransformNode
  18489. */
  18490. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18491. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18492. this._pivotMatrix = matrix.clone();
  18493. this._cache.pivotMatrixUpdated = true;
  18494. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18495. if (this._postMultiplyPivotMatrix) {
  18496. if (!this._pivotMatrixInverse) {
  18497. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18498. }
  18499. else {
  18500. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18501. }
  18502. }
  18503. return this;
  18504. };
  18505. /**
  18506. * Returns the mesh pivot matrix.
  18507. * Default : Identity.
  18508. * A Matrix is returned.
  18509. */
  18510. TransformNode.prototype.getPivotMatrix = function () {
  18511. return this._pivotMatrix;
  18512. };
  18513. /**
  18514. * Prevents the World matrix to be computed any longer.
  18515. * Returns the TransformNode.
  18516. */
  18517. TransformNode.prototype.freezeWorldMatrix = function () {
  18518. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18519. this.computeWorldMatrix(true);
  18520. this._isWorldMatrixFrozen = true;
  18521. return this;
  18522. };
  18523. /**
  18524. * Allows back the World matrix computation.
  18525. * Returns the TransformNode.
  18526. */
  18527. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18528. this._isWorldMatrixFrozen = false;
  18529. this.computeWorldMatrix(true);
  18530. return this;
  18531. };
  18532. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18533. /**
  18534. * True if the World matrix has been frozen.
  18535. * Returns a boolean.
  18536. */
  18537. get: function () {
  18538. return this._isWorldMatrixFrozen;
  18539. },
  18540. enumerable: true,
  18541. configurable: true
  18542. });
  18543. /**
  18544. * Retuns the mesh absolute position in the World.
  18545. * Returns a Vector3.
  18546. */
  18547. TransformNode.prototype.getAbsolutePosition = function () {
  18548. this.computeWorldMatrix();
  18549. return this._absolutePosition;
  18550. };
  18551. /**
  18552. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18553. * Returns the TransformNode.
  18554. */
  18555. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18556. if (!absolutePosition) {
  18557. return this;
  18558. }
  18559. var absolutePositionX;
  18560. var absolutePositionY;
  18561. var absolutePositionZ;
  18562. if (absolutePosition.x === undefined) {
  18563. if (arguments.length < 3) {
  18564. return this;
  18565. }
  18566. absolutePositionX = arguments[0];
  18567. absolutePositionY = arguments[1];
  18568. absolutePositionZ = arguments[2];
  18569. }
  18570. else {
  18571. absolutePositionX = absolutePosition.x;
  18572. absolutePositionY = absolutePosition.y;
  18573. absolutePositionZ = absolutePosition.z;
  18574. }
  18575. if (this.parent) {
  18576. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18577. invertParentWorldMatrix.invert();
  18578. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18579. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18580. }
  18581. else {
  18582. this.position.x = absolutePositionX;
  18583. this.position.y = absolutePositionY;
  18584. this.position.z = absolutePositionZ;
  18585. }
  18586. return this;
  18587. };
  18588. /**
  18589. * Sets the mesh position in its local space.
  18590. * Returns the TransformNode.
  18591. */
  18592. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18593. this.computeWorldMatrix();
  18594. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18595. return this;
  18596. };
  18597. /**
  18598. * Returns the mesh position in the local space from the current World matrix values.
  18599. * Returns a new Vector3.
  18600. */
  18601. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18602. this.computeWorldMatrix();
  18603. var invLocalWorldMatrix = this._localWorld.clone();
  18604. invLocalWorldMatrix.invert();
  18605. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18606. };
  18607. /**
  18608. * Translates the mesh along the passed Vector3 in its local space.
  18609. * Returns the TransformNode.
  18610. */
  18611. TransformNode.prototype.locallyTranslate = function (vector3) {
  18612. this.computeWorldMatrix(true);
  18613. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18614. return this;
  18615. };
  18616. /**
  18617. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18618. * @param targetPoint the position (must be in same space as current mesh) to look at
  18619. * @param yawCor optional yaw (y-axis) correction in radians
  18620. * @param pitchCor optional pitch (x-axis) correction in radians
  18621. * @param rollCor optional roll (z-axis) correction in radians
  18622. * @param space the choosen space of the target
  18623. * @returns the TransformNode.
  18624. */
  18625. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18626. if (yawCor === void 0) { yawCor = 0; }
  18627. if (pitchCor === void 0) { pitchCor = 0; }
  18628. if (rollCor === void 0) { rollCor = 0; }
  18629. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18630. var dv = TransformNode._lookAtVectorCache;
  18631. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18632. targetPoint.subtractToRef(pos, dv);
  18633. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18634. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18635. var pitch = Math.atan2(dv.y, len);
  18636. if (this.rotationQuaternion) {
  18637. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18638. }
  18639. else {
  18640. this.rotation.x = pitch + pitchCor;
  18641. this.rotation.y = yaw + yawCor;
  18642. this.rotation.z = rollCor;
  18643. }
  18644. return this;
  18645. };
  18646. /**
  18647. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18648. * This Vector3 is expressed in the World space.
  18649. */
  18650. TransformNode.prototype.getDirection = function (localAxis) {
  18651. var result = BABYLON.Vector3.Zero();
  18652. this.getDirectionToRef(localAxis, result);
  18653. return result;
  18654. };
  18655. /**
  18656. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18657. * localAxis is expressed in the mesh local space.
  18658. * result is computed in the Wordl space from the mesh World matrix.
  18659. * Returns the TransformNode.
  18660. */
  18661. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18662. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18663. return this;
  18664. };
  18665. /**
  18666. * Sets a new pivot point to the current node
  18667. * @param point defines the new pivot point to use
  18668. * @param space defines if the point is in world or local space (local by default)
  18669. * @returns the current TransformNode
  18670. */
  18671. TransformNode.prototype.setPivotPoint = function (point, space) {
  18672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18673. if (this.getScene().getRenderId() == 0) {
  18674. this.computeWorldMatrix(true);
  18675. }
  18676. var wm = this.getWorldMatrix();
  18677. if (space == BABYLON.Space.WORLD) {
  18678. var tmat = BABYLON.Tmp.Matrix[0];
  18679. wm.invertToRef(tmat);
  18680. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18681. }
  18682. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18683. };
  18684. /**
  18685. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18686. */
  18687. TransformNode.prototype.getPivotPoint = function () {
  18688. var point = BABYLON.Vector3.Zero();
  18689. this.getPivotPointToRef(point);
  18690. return point;
  18691. };
  18692. /**
  18693. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18694. * Returns the TransformNode.
  18695. */
  18696. TransformNode.prototype.getPivotPointToRef = function (result) {
  18697. result.x = -this._pivotMatrix.m[12];
  18698. result.y = -this._pivotMatrix.m[13];
  18699. result.z = -this._pivotMatrix.m[14];
  18700. return this;
  18701. };
  18702. /**
  18703. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18704. */
  18705. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18706. var point = BABYLON.Vector3.Zero();
  18707. this.getAbsolutePivotPointToRef(point);
  18708. return point;
  18709. };
  18710. /**
  18711. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18712. * Returns the TransformNode.
  18713. */
  18714. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18715. result.x = this._pivotMatrix.m[12];
  18716. result.y = this._pivotMatrix.m[13];
  18717. result.z = this._pivotMatrix.m[14];
  18718. this.getPivotPointToRef(result);
  18719. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18720. return this;
  18721. };
  18722. /**
  18723. * Defines the passed node as the parent of the current node.
  18724. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18725. * Returns the TransformNode.
  18726. */
  18727. TransformNode.prototype.setParent = function (node) {
  18728. if (!node && !this.parent) {
  18729. return this;
  18730. }
  18731. if (!node) {
  18732. var rotation = BABYLON.Tmp.Quaternion[0];
  18733. var position = BABYLON.Tmp.Vector3[0];
  18734. var scale = BABYLON.Tmp.Vector3[1];
  18735. if (this.parent && this.parent.computeWorldMatrix) {
  18736. this.parent.computeWorldMatrix(true);
  18737. }
  18738. this.computeWorldMatrix(true);
  18739. this.getWorldMatrix().decompose(scale, rotation, position);
  18740. if (this.rotationQuaternion) {
  18741. this.rotationQuaternion.copyFrom(rotation);
  18742. }
  18743. else {
  18744. rotation.toEulerAnglesToRef(this.rotation);
  18745. }
  18746. this.scaling.x = scale.x;
  18747. this.scaling.y = scale.y;
  18748. this.scaling.z = scale.z;
  18749. this.position.x = position.x;
  18750. this.position.y = position.y;
  18751. this.position.z = position.z;
  18752. }
  18753. else {
  18754. var rotation = BABYLON.Tmp.Quaternion[0];
  18755. var position = BABYLON.Tmp.Vector3[0];
  18756. var scale = BABYLON.Tmp.Vector3[1];
  18757. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18758. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18759. this.computeWorldMatrix(true);
  18760. node.computeWorldMatrix(true);
  18761. node.getWorldMatrix().invertToRef(invParentMatrix);
  18762. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18763. diffMatrix.decompose(scale, rotation, position);
  18764. if (this.rotationQuaternion) {
  18765. this.rotationQuaternion.copyFrom(rotation);
  18766. }
  18767. else {
  18768. rotation.toEulerAnglesToRef(this.rotation);
  18769. }
  18770. this.position.x = position.x;
  18771. this.position.y = position.y;
  18772. this.position.z = position.z;
  18773. this.scaling.x = scale.x;
  18774. this.scaling.y = scale.y;
  18775. this.scaling.z = scale.z;
  18776. }
  18777. this.parent = node;
  18778. return this;
  18779. };
  18780. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18781. get: function () {
  18782. return this._nonUniformScaling;
  18783. },
  18784. enumerable: true,
  18785. configurable: true
  18786. });
  18787. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18788. if (this._nonUniformScaling === value) {
  18789. return false;
  18790. }
  18791. this._nonUniformScaling = value;
  18792. return true;
  18793. };
  18794. /**
  18795. * Attach the current TransformNode to another TransformNode associated with a bone
  18796. * @param bone Bone affecting the TransformNode
  18797. * @param affectedTransformNode TransformNode associated with the bone
  18798. */
  18799. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18800. this._transformToBoneReferal = affectedTransformNode;
  18801. this.parent = bone;
  18802. if (bone.getWorldMatrix().determinant() < 0) {
  18803. this.scalingDeterminant *= -1;
  18804. }
  18805. return this;
  18806. };
  18807. TransformNode.prototype.detachFromBone = function () {
  18808. if (!this.parent) {
  18809. return this;
  18810. }
  18811. if (this.parent.getWorldMatrix().determinant() < 0) {
  18812. this.scalingDeterminant *= -1;
  18813. }
  18814. this._transformToBoneReferal = null;
  18815. this.parent = null;
  18816. return this;
  18817. };
  18818. /**
  18819. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18820. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18821. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18822. * The passed axis is also normalized.
  18823. * Returns the TransformNode.
  18824. */
  18825. TransformNode.prototype.rotate = function (axis, amount, space) {
  18826. axis.normalize();
  18827. if (!this.rotationQuaternion) {
  18828. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18829. this.rotation = BABYLON.Vector3.Zero();
  18830. }
  18831. var rotationQuaternion;
  18832. if (!space || space === BABYLON.Space.LOCAL) {
  18833. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18834. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18835. }
  18836. else {
  18837. if (this.parent) {
  18838. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18839. invertParentWorldMatrix.invert();
  18840. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18841. }
  18842. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18843. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18844. }
  18845. return this;
  18846. };
  18847. /**
  18848. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18849. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18850. * The passed axis is also normalized.
  18851. * Returns the TransformNode.
  18852. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18853. */
  18854. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18855. axis.normalize();
  18856. if (!this.rotationQuaternion) {
  18857. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18858. this.rotation.copyFromFloats(0, 0, 0);
  18859. }
  18860. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18861. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18862. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18863. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18864. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18865. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18866. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18867. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18868. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18869. return this;
  18870. };
  18871. /**
  18872. * Translates the mesh along the axis vector for the passed distance in the given space.
  18873. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18874. * Returns the TransformNode.
  18875. */
  18876. TransformNode.prototype.translate = function (axis, distance, space) {
  18877. var displacementVector = axis.scale(distance);
  18878. if (!space || space === BABYLON.Space.LOCAL) {
  18879. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18880. this.setPositionWithLocalVector(tempV3);
  18881. }
  18882. else {
  18883. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18884. }
  18885. return this;
  18886. };
  18887. /**
  18888. * Adds a rotation step to the mesh current rotation.
  18889. * x, y, z are Euler angles expressed in radians.
  18890. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18891. * This means this rotation is made in the mesh local space only.
  18892. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18893. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18894. * ```javascript
  18895. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18896. * ```
  18897. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18898. * 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.
  18899. * Returns the TransformNode.
  18900. */
  18901. TransformNode.prototype.addRotation = function (x, y, z) {
  18902. var rotationQuaternion;
  18903. if (this.rotationQuaternion) {
  18904. rotationQuaternion = this.rotationQuaternion;
  18905. }
  18906. else {
  18907. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18908. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18909. }
  18910. var accumulation = BABYLON.Tmp.Quaternion[0];
  18911. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18912. rotationQuaternion.multiplyInPlace(accumulation);
  18913. if (!this.rotationQuaternion) {
  18914. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18915. }
  18916. return this;
  18917. };
  18918. /**
  18919. * Computes the mesh World matrix and returns it.
  18920. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18921. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18922. * If the parameter `force`is set to `true`, the actual computation is done.
  18923. * Returns the mesh World Matrix.
  18924. */
  18925. TransformNode.prototype.computeWorldMatrix = function (force) {
  18926. if (this._isWorldMatrixFrozen) {
  18927. return this._worldMatrix;
  18928. }
  18929. if (!force && this.isSynchronized(true)) {
  18930. this._currentRenderId = this.getScene().getRenderId();
  18931. return this._worldMatrix;
  18932. }
  18933. this._cache.position.copyFrom(this.position);
  18934. this._cache.scaling.copyFrom(this.scaling);
  18935. this._cache.pivotMatrixUpdated = false;
  18936. this._cache.billboardMode = this.billboardMode;
  18937. this._currentRenderId = this.getScene().getRenderId();
  18938. this._childRenderId = this.getScene().getRenderId();
  18939. this._isDirty = false;
  18940. // Scaling
  18941. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18942. // Rotation
  18943. //rotate, if quaternion is set and rotation was used
  18944. if (this.rotationQuaternion) {
  18945. var len = this.rotation.length();
  18946. if (len) {
  18947. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18948. this.rotation.copyFromFloats(0, 0, 0);
  18949. }
  18950. }
  18951. if (this.rotationQuaternion) {
  18952. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18953. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18954. }
  18955. else {
  18956. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18957. this._cache.rotation.copyFrom(this.rotation);
  18958. }
  18959. // Translation
  18960. var camera = this.getScene().activeCamera;
  18961. if (this.infiniteDistance && !this.parent && camera) {
  18962. var cameraWorldMatrix = camera.getWorldMatrix();
  18963. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18964. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18965. }
  18966. else {
  18967. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18968. }
  18969. // Composing transformations
  18970. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18971. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18972. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18973. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18974. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18975. // Need to decompose each rotation here
  18976. var currentPosition = BABYLON.Tmp.Vector3[3];
  18977. if (this.parent && this.parent.getWorldMatrix) {
  18978. if (this._transformToBoneReferal) {
  18979. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18980. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18981. }
  18982. else {
  18983. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18984. }
  18985. }
  18986. else {
  18987. currentPosition.copyFrom(this.position);
  18988. }
  18989. currentPosition.subtractInPlace(camera.globalPosition);
  18990. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18991. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18992. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18993. }
  18994. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18995. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18996. }
  18997. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18998. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18999. }
  19000. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19001. }
  19002. else {
  19003. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19004. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19005. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19006. }
  19007. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19008. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19009. }
  19010. // Post multiply inverse of pivotMatrix
  19011. if (this._postMultiplyPivotMatrix) {
  19012. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19013. }
  19014. // Local world
  19015. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19016. // Parent
  19017. if (this.parent && this.parent.getWorldMatrix) {
  19018. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19019. if (this._transformToBoneReferal) {
  19020. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19021. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19022. }
  19023. else {
  19024. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19025. }
  19026. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19027. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19028. this._worldMatrix.copyFrom(this._localWorld);
  19029. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19030. }
  19031. else {
  19032. if (this._transformToBoneReferal) {
  19033. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19034. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19035. }
  19036. else {
  19037. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19038. }
  19039. }
  19040. this._markSyncedWithParent();
  19041. }
  19042. else {
  19043. this._worldMatrix.copyFrom(this._localWorld);
  19044. }
  19045. // Normal matrix
  19046. if (!this.ignoreNonUniformScaling) {
  19047. if (this.scaling.isNonUniform) {
  19048. this._updateNonUniformScalingState(true);
  19049. }
  19050. else if (this.parent && this.parent._nonUniformScaling) {
  19051. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19052. }
  19053. else {
  19054. this._updateNonUniformScalingState(false);
  19055. }
  19056. }
  19057. else {
  19058. this._updateNonUniformScalingState(false);
  19059. }
  19060. this._afterComputeWorldMatrix();
  19061. // Absolute position
  19062. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19063. // Callbacks
  19064. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19065. if (!this._poseMatrix) {
  19066. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19067. }
  19068. // Cache the determinant
  19069. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19070. return this._worldMatrix;
  19071. };
  19072. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19073. };
  19074. /**
  19075. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19076. * @param func: callback function to add
  19077. *
  19078. * Returns the TransformNode.
  19079. */
  19080. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19081. this.onAfterWorldMatrixUpdateObservable.add(func);
  19082. return this;
  19083. };
  19084. /**
  19085. * Removes a registered callback function.
  19086. * Returns the TransformNode.
  19087. */
  19088. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19089. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19090. return this;
  19091. };
  19092. /**
  19093. * Clone the current transform node
  19094. * Returns the new transform node
  19095. * @param name Name of the new clone
  19096. * @param newParent New parent for the clone
  19097. * @param doNotCloneChildren Do not clone children hierarchy
  19098. */
  19099. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19100. var _this = this;
  19101. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19102. result.name = name;
  19103. result.id = name;
  19104. if (newParent) {
  19105. result.parent = newParent;
  19106. }
  19107. if (!doNotCloneChildren) {
  19108. // Children
  19109. var directDescendants = this.getDescendants(true);
  19110. for (var index = 0; index < directDescendants.length; index++) {
  19111. var child = directDescendants[index];
  19112. if (child.clone) {
  19113. child.clone(name + "." + child.name, result);
  19114. }
  19115. }
  19116. }
  19117. return result;
  19118. };
  19119. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19120. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19121. serializationObject.type = this.getClassName();
  19122. // Parent
  19123. if (this.parent) {
  19124. serializationObject.parentId = this.parent.id;
  19125. }
  19126. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19127. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19128. }
  19129. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19130. serializationObject.isEnabled = this.isEnabled();
  19131. // Parent
  19132. if (this.parent) {
  19133. serializationObject.parentId = this.parent.id;
  19134. }
  19135. return serializationObject;
  19136. };
  19137. // Statics
  19138. /**
  19139. * Returns a new TransformNode object parsed from the source provided.
  19140. * The parameter `parsedMesh` is the source.
  19141. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19142. */
  19143. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19144. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19145. if (BABYLON.Tags) {
  19146. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19147. }
  19148. if (parsedTransformNode.localMatrix) {
  19149. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19150. }
  19151. else if (parsedTransformNode.pivotMatrix) {
  19152. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19153. }
  19154. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19155. // Parent
  19156. if (parsedTransformNode.parentId) {
  19157. transformNode._waitingParentId = parsedTransformNode.parentId;
  19158. }
  19159. return transformNode;
  19160. };
  19161. /**
  19162. * Releases resources associated with this transform node.
  19163. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19164. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19165. */
  19166. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19167. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19168. // Animations
  19169. this.getScene().stopAnimation(this);
  19170. // Remove from scene
  19171. this.getScene().removeTransformNode(this);
  19172. this.onAfterWorldMatrixUpdateObservable.clear();
  19173. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19174. };
  19175. // Statics
  19176. TransformNode.BILLBOARDMODE_NONE = 0;
  19177. TransformNode.BILLBOARDMODE_X = 1;
  19178. TransformNode.BILLBOARDMODE_Y = 2;
  19179. TransformNode.BILLBOARDMODE_Z = 4;
  19180. TransformNode.BILLBOARDMODE_ALL = 7;
  19181. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19182. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19183. __decorate([
  19184. BABYLON.serializeAsVector3()
  19185. ], TransformNode.prototype, "_rotation", void 0);
  19186. __decorate([
  19187. BABYLON.serializeAsQuaternion()
  19188. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19189. __decorate([
  19190. BABYLON.serializeAsVector3()
  19191. ], TransformNode.prototype, "_scaling", void 0);
  19192. __decorate([
  19193. BABYLON.serialize()
  19194. ], TransformNode.prototype, "billboardMode", void 0);
  19195. __decorate([
  19196. BABYLON.serialize()
  19197. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19198. __decorate([
  19199. BABYLON.serialize()
  19200. ], TransformNode.prototype, "infiniteDistance", void 0);
  19201. __decorate([
  19202. BABYLON.serialize()
  19203. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19204. __decorate([
  19205. BABYLON.serializeAsVector3()
  19206. ], TransformNode.prototype, "position", void 0);
  19207. return TransformNode;
  19208. }(BABYLON.Node));
  19209. BABYLON.TransformNode = TransformNode;
  19210. })(BABYLON || (BABYLON = {}));
  19211. //# sourceMappingURL=babylon.transformNode.js.map
  19212. var BABYLON;
  19213. (function (BABYLON) {
  19214. /**
  19215. * Class used to store all common mesh properties
  19216. */
  19217. var AbstractMesh = /** @class */ (function (_super) {
  19218. __extends(AbstractMesh, _super);
  19219. // Constructor
  19220. /**
  19221. * Creates a new AbstractMesh
  19222. * @param name defines the name of the mesh
  19223. * @param scene defines the hosting scene
  19224. */
  19225. function AbstractMesh(name, scene) {
  19226. if (scene === void 0) { scene = null; }
  19227. var _this = _super.call(this, name, scene, false) || this;
  19228. _this._facetNb = 0; // facet number
  19229. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19230. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19231. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19232. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19233. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19234. _this._subDiv = {
  19235. max: 1,
  19236. X: 1,
  19237. Y: 1,
  19238. Z: 1
  19239. };
  19240. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19241. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19242. // Events
  19243. /**
  19244. * An event triggered when this mesh collides with another one
  19245. */
  19246. _this.onCollideObservable = new BABYLON.Observable();
  19247. /**
  19248. * An event triggered when the collision's position changes
  19249. */
  19250. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19251. /**
  19252. * An event triggered when material is changed
  19253. */
  19254. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19255. // Properties
  19256. /**
  19257. * Gets or sets the orientation for POV movement & rotation
  19258. */
  19259. _this.definedFacingForward = true;
  19260. /**
  19261. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19262. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19263. * * 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.
  19264. * @see http://doc.babylonjs.com/features/occlusionquery
  19265. */
  19266. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19267. /**
  19268. * 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:
  19269. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19270. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19271. * * 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.
  19272. * @see http://doc.babylonjs.com/features/occlusionquery
  19273. */
  19274. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19275. /**
  19276. * 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.
  19277. * The default value is -1 which means don't break the query and wait till the result
  19278. * @see http://doc.babylonjs.com/features/occlusionquery
  19279. */
  19280. _this.occlusionRetryCount = -1;
  19281. /** @hidden */
  19282. _this._occlusionInternalRetryCounter = 0;
  19283. /** @hidden */
  19284. _this._isOccluded = false;
  19285. /** @hidden */
  19286. _this._isOcclusionQueryInProgress = false;
  19287. _this._visibility = 1.0;
  19288. /** Gets or sets the alpha index used to sort transparent meshes
  19289. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19290. */
  19291. _this.alphaIndex = Number.MAX_VALUE;
  19292. /**
  19293. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19294. */
  19295. _this.isVisible = true;
  19296. /**
  19297. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19298. */
  19299. _this.isPickable = true;
  19300. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19301. _this.showSubMeshesBoundingBox = false;
  19302. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19303. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19304. */
  19305. _this.isBlocker = false;
  19306. /**
  19307. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19308. */
  19309. _this.enablePointerMoveEvents = false;
  19310. /**
  19311. * Specifies the rendering group id for this mesh (0 by default)
  19312. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19313. */
  19314. _this.renderingGroupId = 0;
  19315. _this._receiveShadows = false;
  19316. /**
  19317. * Gets or sets a boolean indicating if the outline must be rendered as well
  19318. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19319. */
  19320. _this.renderOutline = false;
  19321. /** Defines color to use when rendering outline */
  19322. _this.outlineColor = BABYLON.Color3.Red();
  19323. /** Define width to use when rendering outline */
  19324. _this.outlineWidth = 0.02;
  19325. /**
  19326. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19327. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19328. */
  19329. _this.renderOverlay = false;
  19330. /** Defines color to use when rendering overlay */
  19331. _this.overlayColor = BABYLON.Color3.Red();
  19332. /** Defines alpha to use when rendering overlay */
  19333. _this.overlayAlpha = 0.5;
  19334. _this._hasVertexAlpha = false;
  19335. _this._useVertexColors = true;
  19336. _this._computeBonesUsingShaders = true;
  19337. _this._numBoneInfluencers = 4;
  19338. _this._applyFog = true;
  19339. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19340. _this.useOctreeForRenderingSelection = true;
  19341. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19342. _this.useOctreeForPicking = true;
  19343. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19344. _this.useOctreeForCollisions = true;
  19345. _this._layerMask = 0x0FFFFFFF;
  19346. /**
  19347. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19348. */
  19349. _this.alwaysSelectAsActiveMesh = false;
  19350. /**
  19351. * Gets or sets the current action manager
  19352. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19353. */
  19354. _this.actionManager = null;
  19355. /**
  19356. * Gets or sets impostor used for physic simulation
  19357. * @see http://doc.babylonjs.com/features/physics_engine
  19358. */
  19359. _this.physicsImpostor = null;
  19360. // Collisions
  19361. _this._checkCollisions = false;
  19362. _this._collisionMask = -1;
  19363. _this._collisionGroup = -1;
  19364. /**
  19365. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19366. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19367. */
  19368. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19369. /**
  19370. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19371. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19372. */
  19373. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19374. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19375. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19376. // Edges
  19377. /**
  19378. * Defines edge width used when edgesRenderer is enabled
  19379. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19380. */
  19381. _this.edgesWidth = 1;
  19382. /**
  19383. * Defines edge color used when edgesRenderer is enabled
  19384. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19385. */
  19386. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19387. // Cache
  19388. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19389. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19390. /** @hidden */
  19391. _this._renderId = 0;
  19392. /** @hidden */
  19393. _this._intersectionsInProgress = new Array();
  19394. /** @hidden */
  19395. _this._unIndexed = false;
  19396. /** @hidden */
  19397. _this._lightSources = new Array();
  19398. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19399. if (collidedMesh === void 0) { collidedMesh = null; }
  19400. //TODO move this to the collision coordinator!
  19401. if (_this.getScene().workerCollisions)
  19402. newPosition.multiplyInPlace(_this._collider._radius);
  19403. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19404. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19405. _this.position.addInPlace(_this._diffPositionForCollisions);
  19406. }
  19407. if (collidedMesh) {
  19408. _this.onCollideObservable.notifyObservers(collidedMesh);
  19409. }
  19410. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19411. };
  19412. _this.getScene().addMesh(_this);
  19413. _this._resyncLightSources();
  19414. return _this;
  19415. }
  19416. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19417. /**
  19418. * No billboard
  19419. */
  19420. get: function () {
  19421. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19422. },
  19423. enumerable: true,
  19424. configurable: true
  19425. });
  19426. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19427. /** Billboard on X axis */
  19428. get: function () {
  19429. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19430. },
  19431. enumerable: true,
  19432. configurable: true
  19433. });
  19434. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19435. /** Billboard on Y axis */
  19436. get: function () {
  19437. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19438. },
  19439. enumerable: true,
  19440. configurable: true
  19441. });
  19442. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19443. /** Billboard on Z axis */
  19444. get: function () {
  19445. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19446. },
  19447. enumerable: true,
  19448. configurable: true
  19449. });
  19450. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19451. /** Billboard on all axes */
  19452. get: function () {
  19453. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19459. /**
  19460. * Gets the number of facets in the mesh
  19461. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19462. */
  19463. get: function () {
  19464. return this._facetNb;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19470. /**
  19471. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19472. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19473. */
  19474. get: function () {
  19475. return this._partitioningSubdivisions;
  19476. },
  19477. set: function (nb) {
  19478. this._partitioningSubdivisions = nb;
  19479. },
  19480. enumerable: true,
  19481. configurable: true
  19482. });
  19483. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19484. /**
  19485. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19486. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19487. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19488. */
  19489. get: function () {
  19490. return this._partitioningBBoxRatio;
  19491. },
  19492. set: function (ratio) {
  19493. this._partitioningBBoxRatio = ratio;
  19494. },
  19495. enumerable: true,
  19496. configurable: true
  19497. });
  19498. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19499. /**
  19500. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19501. * Works only for updatable meshes.
  19502. * Doesn't work with multi-materials
  19503. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19504. */
  19505. get: function () {
  19506. return this._facetDepthSort;
  19507. },
  19508. set: function (sort) {
  19509. this._facetDepthSort = sort;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19515. /**
  19516. * The location (Vector3) where the facet depth sort must be computed from.
  19517. * By default, the active camera position.
  19518. * Used only when facet depth sort is enabled
  19519. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19520. */
  19521. get: function () {
  19522. return this._facetDepthSortFrom;
  19523. },
  19524. set: function (location) {
  19525. this._facetDepthSortFrom = location;
  19526. },
  19527. enumerable: true,
  19528. configurable: true
  19529. });
  19530. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19531. /**
  19532. * gets a boolean indicating if facetData is enabled
  19533. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19534. */
  19535. get: function () {
  19536. return this._facetDataEnabled;
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. /** @hidden */
  19542. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19543. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19544. return false;
  19545. }
  19546. this._markSubMeshesAsMiscDirty();
  19547. return true;
  19548. };
  19549. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19550. /** Set a function to call when this mesh collides with another one */
  19551. set: function (callback) {
  19552. if (this._onCollideObserver) {
  19553. this.onCollideObservable.remove(this._onCollideObserver);
  19554. }
  19555. this._onCollideObserver = this.onCollideObservable.add(callback);
  19556. },
  19557. enumerable: true,
  19558. configurable: true
  19559. });
  19560. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19561. /** Set a function to call when the collision's position changes */
  19562. set: function (callback) {
  19563. if (this._onCollisionPositionChangeObserver) {
  19564. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19565. }
  19566. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19567. },
  19568. enumerable: true,
  19569. configurable: true
  19570. });
  19571. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19572. /**
  19573. * 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
  19574. * @see http://doc.babylonjs.com/features/occlusionquery
  19575. */
  19576. get: function () {
  19577. return this._isOccluded;
  19578. },
  19579. set: function (value) {
  19580. this._isOccluded = value;
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19586. /**
  19587. * Flag to check the progress status of the query
  19588. * @see http://doc.babylonjs.com/features/occlusionquery
  19589. */
  19590. get: function () {
  19591. return this._isOcclusionQueryInProgress;
  19592. },
  19593. enumerable: true,
  19594. configurable: true
  19595. });
  19596. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19597. /**
  19598. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19599. */
  19600. get: function () {
  19601. return this._visibility;
  19602. },
  19603. /**
  19604. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19605. */
  19606. set: function (value) {
  19607. if (this._visibility === value) {
  19608. return;
  19609. }
  19610. this._visibility = value;
  19611. this._markSubMeshesAsMiscDirty();
  19612. },
  19613. enumerable: true,
  19614. configurable: true
  19615. });
  19616. Object.defineProperty(AbstractMesh.prototype, "material", {
  19617. /** Gets or sets current material */
  19618. get: function () {
  19619. return this._material;
  19620. },
  19621. set: function (value) {
  19622. if (this._material === value) {
  19623. return;
  19624. }
  19625. this._material = value;
  19626. if (this.onMaterialChangedObservable.hasObservers) {
  19627. this.onMaterialChangedObservable.notifyObservers(this);
  19628. }
  19629. if (!this.subMeshes) {
  19630. return;
  19631. }
  19632. this._unBindEffect();
  19633. },
  19634. enumerable: true,
  19635. configurable: true
  19636. });
  19637. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19638. /**
  19639. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19640. * @see http://doc.babylonjs.com/babylon101/shadows
  19641. */
  19642. get: function () {
  19643. return this._receiveShadows;
  19644. },
  19645. set: function (value) {
  19646. if (this._receiveShadows === value) {
  19647. return;
  19648. }
  19649. this._receiveShadows = value;
  19650. this._markSubMeshesAsLightDirty();
  19651. },
  19652. enumerable: true,
  19653. configurable: true
  19654. });
  19655. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19656. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19657. get: function () {
  19658. return this._hasVertexAlpha;
  19659. },
  19660. set: function (value) {
  19661. if (this._hasVertexAlpha === value) {
  19662. return;
  19663. }
  19664. this._hasVertexAlpha = value;
  19665. this._markSubMeshesAsAttributesDirty();
  19666. this._markSubMeshesAsMiscDirty();
  19667. },
  19668. enumerable: true,
  19669. configurable: true
  19670. });
  19671. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19672. /** 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) */
  19673. get: function () {
  19674. return this._useVertexColors;
  19675. },
  19676. set: function (value) {
  19677. if (this._useVertexColors === value) {
  19678. return;
  19679. }
  19680. this._useVertexColors = value;
  19681. this._markSubMeshesAsAttributesDirty();
  19682. },
  19683. enumerable: true,
  19684. configurable: true
  19685. });
  19686. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19687. /**
  19688. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19689. */
  19690. get: function () {
  19691. return this._computeBonesUsingShaders;
  19692. },
  19693. set: function (value) {
  19694. if (this._computeBonesUsingShaders === value) {
  19695. return;
  19696. }
  19697. this._computeBonesUsingShaders = value;
  19698. this._markSubMeshesAsAttributesDirty();
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19704. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19705. get: function () {
  19706. return this._numBoneInfluencers;
  19707. },
  19708. set: function (value) {
  19709. if (this._numBoneInfluencers === value) {
  19710. return;
  19711. }
  19712. this._numBoneInfluencers = value;
  19713. this._markSubMeshesAsAttributesDirty();
  19714. },
  19715. enumerable: true,
  19716. configurable: true
  19717. });
  19718. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19719. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19720. get: function () {
  19721. return this._applyFog;
  19722. },
  19723. set: function (value) {
  19724. if (this._applyFog === value) {
  19725. return;
  19726. }
  19727. this._applyFog = value;
  19728. this._markSubMeshesAsMiscDirty();
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19734. /**
  19735. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19736. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19737. */
  19738. get: function () {
  19739. return this._layerMask;
  19740. },
  19741. set: function (value) {
  19742. if (value === this._layerMask) {
  19743. return;
  19744. }
  19745. this._layerMask = value;
  19746. this._resyncLightSources();
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19752. /**
  19753. * Gets or sets a collision mask used to mask collisions (default is -1).
  19754. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19755. */
  19756. get: function () {
  19757. return this._collisionMask;
  19758. },
  19759. set: function (mask) {
  19760. this._collisionMask = !isNaN(mask) ? mask : -1;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19766. /**
  19767. * Gets or sets the current collision group mask (-1 by default).
  19768. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19769. */
  19770. get: function () {
  19771. return this._collisionGroup;
  19772. },
  19773. set: function (mask) {
  19774. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19780. /** @hidden */
  19781. get: function () {
  19782. return null;
  19783. },
  19784. enumerable: true,
  19785. configurable: true
  19786. });
  19787. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19788. get: function () {
  19789. return this._skeleton;
  19790. },
  19791. /**
  19792. * Gets or sets a skeleton to apply skining transformations
  19793. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19794. */
  19795. set: function (value) {
  19796. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19797. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19798. }
  19799. if (value && value.needInitialSkinMatrix) {
  19800. value._registerMeshWithPoseMatrix(this);
  19801. }
  19802. this._skeleton = value;
  19803. if (!this._skeleton) {
  19804. this._bonesTransformMatrices = null;
  19805. }
  19806. this._markSubMeshesAsAttributesDirty();
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. /**
  19812. * Returns the string "AbstractMesh"
  19813. * @returns "AbstractMesh"
  19814. */
  19815. AbstractMesh.prototype.getClassName = function () {
  19816. return "AbstractMesh";
  19817. };
  19818. /**
  19819. * Gets a string representation of the current mesh
  19820. * @param fullDetails defines a boolean indicating if full details must be included
  19821. * @returns a string representation of the current mesh
  19822. */
  19823. AbstractMesh.prototype.toString = function (fullDetails) {
  19824. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19825. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19826. if (this._skeleton) {
  19827. ret += ", skeleton: " + this._skeleton.name;
  19828. }
  19829. if (fullDetails) {
  19830. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19831. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19832. }
  19833. return ret;
  19834. };
  19835. /** @hidden */
  19836. AbstractMesh.prototype._rebuild = function () {
  19837. if (this._occlusionQuery) {
  19838. this._occlusionQuery = null;
  19839. }
  19840. if (this._edgesRenderer) {
  19841. this._edgesRenderer._rebuild();
  19842. }
  19843. if (!this.subMeshes) {
  19844. return;
  19845. }
  19846. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19847. var subMesh = _a[_i];
  19848. subMesh._rebuild();
  19849. }
  19850. };
  19851. /** @hidden */
  19852. AbstractMesh.prototype._resyncLightSources = function () {
  19853. this._lightSources.length = 0;
  19854. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19855. var light = _a[_i];
  19856. if (!light.isEnabled()) {
  19857. continue;
  19858. }
  19859. if (light.canAffectMesh(this)) {
  19860. this._lightSources.push(light);
  19861. }
  19862. }
  19863. this._markSubMeshesAsLightDirty();
  19864. };
  19865. /** @hidden */
  19866. AbstractMesh.prototype._resyncLighSource = function (light) {
  19867. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19868. var index = this._lightSources.indexOf(light);
  19869. if (index === -1) {
  19870. if (!isIn) {
  19871. return;
  19872. }
  19873. this._lightSources.push(light);
  19874. }
  19875. else {
  19876. if (isIn) {
  19877. return;
  19878. }
  19879. this._lightSources.splice(index, 1);
  19880. }
  19881. this._markSubMeshesAsLightDirty();
  19882. };
  19883. /** @hidden */
  19884. AbstractMesh.prototype._unBindEffect = function () {
  19885. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19886. var subMesh = _a[_i];
  19887. subMesh.setEffect(null);
  19888. }
  19889. };
  19890. /** @hidden */
  19891. AbstractMesh.prototype._removeLightSource = function (light) {
  19892. var index = this._lightSources.indexOf(light);
  19893. if (index === -1) {
  19894. return;
  19895. }
  19896. this._lightSources.splice(index, 1);
  19897. this._markSubMeshesAsLightDirty();
  19898. };
  19899. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19900. if (!this.subMeshes) {
  19901. return;
  19902. }
  19903. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19904. var subMesh = _a[_i];
  19905. if (subMesh._materialDefines) {
  19906. func(subMesh._materialDefines);
  19907. }
  19908. }
  19909. };
  19910. /** @hidden */
  19911. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19912. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19913. };
  19914. /** @hidden */
  19915. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19916. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19917. };
  19918. /** @hidden */
  19919. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19920. if (!this.subMeshes) {
  19921. return;
  19922. }
  19923. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19924. var subMesh = _a[_i];
  19925. var material = subMesh.getMaterial();
  19926. if (material) {
  19927. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19928. }
  19929. }
  19930. };
  19931. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19932. /**
  19933. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19934. */
  19935. get: function () {
  19936. return this._scaling;
  19937. },
  19938. set: function (newScaling) {
  19939. this._scaling = newScaling;
  19940. if (this.physicsImpostor) {
  19941. this.physicsImpostor.forceUpdate();
  19942. }
  19943. },
  19944. enumerable: true,
  19945. configurable: true
  19946. });
  19947. // Methods
  19948. /**
  19949. * Disables the mesh edge rendering mode
  19950. * @returns the currentAbstractMesh
  19951. */
  19952. AbstractMesh.prototype.disableEdgesRendering = function () {
  19953. if (this._edgesRenderer) {
  19954. this._edgesRenderer.dispose();
  19955. this._edgesRenderer = null;
  19956. }
  19957. return this;
  19958. };
  19959. /**
  19960. * Enables the edge rendering mode on the mesh.
  19961. * This mode makes the mesh edges visible
  19962. * @param epsilon defines the maximal distance between two angles to detect a face
  19963. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19964. * @returns the currentAbstractMesh
  19965. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19966. */
  19967. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19968. if (epsilon === void 0) { epsilon = 0.95; }
  19969. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19970. this.disableEdgesRendering();
  19971. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19972. return this;
  19973. };
  19974. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  19975. /**
  19976. * Gets the edgesRenderer associated with the mesh
  19977. */
  19978. get: function () {
  19979. return this._edgesRenderer;
  19980. },
  19981. enumerable: true,
  19982. configurable: true
  19983. });
  19984. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19985. /**
  19986. * Returns true if the mesh is blocked. Implemented by child classes
  19987. */
  19988. get: function () {
  19989. return false;
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. /**
  19995. * Returns the mesh itself by default. Implemented by child classes
  19996. * @param camera defines the camera to use to pick the right LOD level
  19997. * @returns the currentAbstractMesh
  19998. */
  19999. AbstractMesh.prototype.getLOD = function (camera) {
  20000. return this;
  20001. };
  20002. /**
  20003. * Returns 0 by default. Implemented by child classes
  20004. * @returns an integer
  20005. */
  20006. AbstractMesh.prototype.getTotalVertices = function () {
  20007. return 0;
  20008. };
  20009. /**
  20010. * Returns null by default. Implemented by child classes
  20011. * @returns null
  20012. */
  20013. AbstractMesh.prototype.getIndices = function () {
  20014. return null;
  20015. };
  20016. /**
  20017. * Returns the array of the requested vertex data kind. Implemented by child classes
  20018. * @param kind defines the vertex data kind to use
  20019. * @returns null
  20020. */
  20021. AbstractMesh.prototype.getVerticesData = function (kind) {
  20022. return null;
  20023. };
  20024. /**
  20025. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20026. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20027. * Note that a new underlying VertexBuffer object is created each call.
  20028. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20029. * @param kind defines vertex data kind:
  20030. * * BABYLON.VertexBuffer.PositionKind
  20031. * * BABYLON.VertexBuffer.UVKind
  20032. * * BABYLON.VertexBuffer.UV2Kind
  20033. * * BABYLON.VertexBuffer.UV3Kind
  20034. * * BABYLON.VertexBuffer.UV4Kind
  20035. * * BABYLON.VertexBuffer.UV5Kind
  20036. * * BABYLON.VertexBuffer.UV6Kind
  20037. * * BABYLON.VertexBuffer.ColorKind
  20038. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20039. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20040. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20041. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20042. * @param data defines the data source
  20043. * @param updatable defines if the data must be flagged as updatable (or static)
  20044. * @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
  20045. * @returns the current mesh
  20046. */
  20047. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20048. return this;
  20049. };
  20050. /**
  20051. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20052. * If the mesh has no geometry, it is simply returned as it is.
  20053. * @param kind defines vertex data kind:
  20054. * * BABYLON.VertexBuffer.PositionKind
  20055. * * BABYLON.VertexBuffer.UVKind
  20056. * * BABYLON.VertexBuffer.UV2Kind
  20057. * * BABYLON.VertexBuffer.UV3Kind
  20058. * * BABYLON.VertexBuffer.UV4Kind
  20059. * * BABYLON.VertexBuffer.UV5Kind
  20060. * * BABYLON.VertexBuffer.UV6Kind
  20061. * * BABYLON.VertexBuffer.ColorKind
  20062. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20063. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20064. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20065. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20066. * @param data defines the data source
  20067. * @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
  20068. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20069. * @returns the current mesh
  20070. */
  20071. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20072. return this;
  20073. };
  20074. /**
  20075. * Sets the mesh indices,
  20076. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20077. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20078. * @param totalVertices Defines the total number of vertices
  20079. * @returns the current mesh
  20080. */
  20081. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20082. return this;
  20083. };
  20084. /**
  20085. * Gets a boolean indicating if specific vertex data is present
  20086. * @param kind defines the vertex data kind to use
  20087. * @returns true is data kind is present
  20088. */
  20089. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20090. return false;
  20091. };
  20092. /**
  20093. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20094. * @returns a BoundingInfo
  20095. */
  20096. AbstractMesh.prototype.getBoundingInfo = function () {
  20097. if (this._masterMesh) {
  20098. return this._masterMesh.getBoundingInfo();
  20099. }
  20100. if (!this._boundingInfo) {
  20101. // this._boundingInfo is being created here
  20102. this._updateBoundingInfo();
  20103. }
  20104. // cannot be null.
  20105. return this._boundingInfo;
  20106. };
  20107. /**
  20108. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20109. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20110. * @returns the current mesh
  20111. */
  20112. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20113. if (includeDescendants === void 0) { includeDescendants = true; }
  20114. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20115. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20116. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20117. if (maxDimension === 0) {
  20118. return this;
  20119. }
  20120. var scale = 1 / maxDimension;
  20121. this.scaling.scaleInPlace(scale);
  20122. return this;
  20123. };
  20124. /**
  20125. * Overwrite the current bounding info
  20126. * @param boundingInfo defines the new bounding info
  20127. * @returns the current mesh
  20128. */
  20129. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20130. this._boundingInfo = boundingInfo;
  20131. return this;
  20132. };
  20133. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20134. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20135. get: function () {
  20136. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. /** @hidden */
  20142. AbstractMesh.prototype._preActivate = function () {
  20143. };
  20144. /** @hidden */
  20145. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20146. };
  20147. /** @hidden */
  20148. AbstractMesh.prototype._activate = function (renderId) {
  20149. this._renderId = renderId;
  20150. };
  20151. /**
  20152. * Gets the current world matrix
  20153. * @returns a Matrix
  20154. */
  20155. AbstractMesh.prototype.getWorldMatrix = function () {
  20156. if (this._masterMesh) {
  20157. return this._masterMesh.getWorldMatrix();
  20158. }
  20159. return _super.prototype.getWorldMatrix.call(this);
  20160. };
  20161. /** @hidden */
  20162. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20163. if (this._masterMesh) {
  20164. return this._masterMesh._getWorldMatrixDeterminant();
  20165. }
  20166. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20167. };
  20168. // ================================== Point of View Movement =================================
  20169. /**
  20170. * Perform relative position change from the point of view of behind the front of the mesh.
  20171. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20172. * Supports definition of mesh facing forward or backward
  20173. * @param amountRight defines the distance on the right axis
  20174. * @param amountUp defines the distance on the up axis
  20175. * @param amountForward defines the distance on the forward axis
  20176. * @returns the current mesh
  20177. */
  20178. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20179. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20180. return this;
  20181. };
  20182. /**
  20183. * Calculate relative position change from the point of view of behind the front of the mesh.
  20184. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20185. * Supports definition of mesh facing forward or backward
  20186. * @param amountRight defines the distance on the right axis
  20187. * @param amountUp defines the distance on the up axis
  20188. * @param amountForward defines the distance on the forward axis
  20189. * @returns the new displacement vector
  20190. */
  20191. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20192. var rotMatrix = new BABYLON.Matrix();
  20193. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20194. rotQuaternion.toRotationMatrix(rotMatrix);
  20195. var translationDelta = BABYLON.Vector3.Zero();
  20196. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20197. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20198. return translationDelta;
  20199. };
  20200. // ================================== Point of View Rotation =================================
  20201. /**
  20202. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20203. * Supports definition of mesh facing forward or backward
  20204. * @param flipBack defines the flip
  20205. * @param twirlClockwise defines the twirl
  20206. * @param tiltRight defines the tilt
  20207. * @returns the current mesh
  20208. */
  20209. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20210. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20211. return this;
  20212. };
  20213. /**
  20214. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20215. * Supports definition of mesh facing forward or backward.
  20216. * @param flipBack defines the flip
  20217. * @param twirlClockwise defines the twirl
  20218. * @param tiltRight defines the tilt
  20219. * @returns the new rotation vector
  20220. */
  20221. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20222. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20223. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20224. };
  20225. /**
  20226. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20227. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20228. * @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
  20229. * @returns the new bounding vectors
  20230. */
  20231. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20232. if (includeDescendants === void 0) { includeDescendants = true; }
  20233. if (predicate === void 0) { predicate = null; }
  20234. // Ensures that all world matrix will be recomputed.
  20235. this.getScene().incrementRenderId();
  20236. this.computeWorldMatrix(true);
  20237. var min;
  20238. var max;
  20239. var boundingInfo = this.getBoundingInfo();
  20240. if (!this.subMeshes) {
  20241. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20242. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20243. }
  20244. else {
  20245. min = boundingInfo.boundingBox.minimumWorld;
  20246. max = boundingInfo.boundingBox.maximumWorld;
  20247. }
  20248. if (includeDescendants) {
  20249. var descendants = this.getDescendants(false);
  20250. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20251. var descendant = descendants_1[_i];
  20252. var childMesh = descendant;
  20253. childMesh.computeWorldMatrix(true);
  20254. // Filters meshes based on custom predicate function.
  20255. if (predicate && !predicate(childMesh)) {
  20256. continue;
  20257. }
  20258. //make sure we have the needed params to get mix and max
  20259. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20260. continue;
  20261. }
  20262. var childBoundingInfo = childMesh.getBoundingInfo();
  20263. var boundingBox = childBoundingInfo.boundingBox;
  20264. var minBox = boundingBox.minimumWorld;
  20265. var maxBox = boundingBox.maximumWorld;
  20266. BABYLON.Tools.CheckExtends(minBox, min, max);
  20267. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20268. }
  20269. }
  20270. return {
  20271. min: min,
  20272. max: max
  20273. };
  20274. };
  20275. /** @hidden */
  20276. AbstractMesh.prototype._updateBoundingInfo = function () {
  20277. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20278. this._boundingInfo.update(this.worldMatrixFromCache);
  20279. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20280. return this;
  20281. };
  20282. /** @hidden */
  20283. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20284. if (!this.subMeshes) {
  20285. return this;
  20286. }
  20287. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20288. var subMesh = this.subMeshes[subIndex];
  20289. if (!subMesh.IsGlobal) {
  20290. subMesh.updateBoundingInfo(matrix);
  20291. }
  20292. }
  20293. return this;
  20294. };
  20295. /** @hidden */
  20296. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20297. // Bounding info
  20298. this._updateBoundingInfo();
  20299. };
  20300. /**
  20301. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20302. * A mesh is in the frustum if its bounding box intersects the frustum
  20303. * @param frustumPlanes defines the frustum to test
  20304. * @returns true if the mesh is in the frustum planes
  20305. */
  20306. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20307. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20308. };
  20309. /**
  20310. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20311. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20312. * @param frustumPlanes defines the frustum to test
  20313. * @returns true if the mesh is completely in the frustum planes
  20314. */
  20315. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20316. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20317. };
  20318. /**
  20319. * True if the mesh intersects another mesh or a SolidParticle object
  20320. * @param mesh defines a target mesh or SolidParticle to test
  20321. * @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)
  20322. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20323. * @returns true if there is an intersection
  20324. */
  20325. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20326. if (precise === void 0) { precise = false; }
  20327. if (!this._boundingInfo || !mesh._boundingInfo) {
  20328. return false;
  20329. }
  20330. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20331. return true;
  20332. }
  20333. if (includeDescendants) {
  20334. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20335. var child = _a[_i];
  20336. if (child.intersectsMesh(mesh, precise, true)) {
  20337. return true;
  20338. }
  20339. }
  20340. }
  20341. return false;
  20342. };
  20343. /**
  20344. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20345. * @param point defines the point to test
  20346. * @returns true if there is an intersection
  20347. */
  20348. AbstractMesh.prototype.intersectsPoint = function (point) {
  20349. if (!this._boundingInfo) {
  20350. return false;
  20351. }
  20352. return this._boundingInfo.intersectsPoint(point);
  20353. };
  20354. /**
  20355. * Gets the current physics impostor
  20356. * @see http://doc.babylonjs.com/features/physics_engine
  20357. * @returns a physics impostor or null
  20358. */
  20359. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20360. return this.physicsImpostor;
  20361. };
  20362. /**
  20363. * Gets the position of the current mesh in camera space
  20364. * @param camera defines the camera to use
  20365. * @returns a position
  20366. */
  20367. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20368. if (camera === void 0) { camera = null; }
  20369. if (!camera) {
  20370. camera = this.getScene().activeCamera;
  20371. }
  20372. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20373. };
  20374. /**
  20375. * Returns the distance from the mesh to the active camera
  20376. * @param camera defines the camera to use
  20377. * @returns the distance
  20378. */
  20379. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20380. if (camera === void 0) { camera = null; }
  20381. if (!camera) {
  20382. camera = this.getScene().activeCamera;
  20383. }
  20384. return this.absolutePosition.subtract(camera.position).length();
  20385. };
  20386. /**
  20387. * Apply a physic impulse to the mesh
  20388. * @param force defines the force to apply
  20389. * @param contactPoint defines where to apply the force
  20390. * @returns the current mesh
  20391. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20392. */
  20393. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20394. if (!this.physicsImpostor) {
  20395. return this;
  20396. }
  20397. this.physicsImpostor.applyImpulse(force, contactPoint);
  20398. return this;
  20399. };
  20400. /**
  20401. * Creates a physic joint between two meshes
  20402. * @param otherMesh defines the other mesh to use
  20403. * @param pivot1 defines the pivot to use on this mesh
  20404. * @param pivot2 defines the pivot to use on the other mesh
  20405. * @param options defines additional options (can be plugin dependent)
  20406. * @returns the current mesh
  20407. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20408. */
  20409. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20410. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20411. return this;
  20412. }
  20413. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20414. mainPivot: pivot1,
  20415. connectedPivot: pivot2,
  20416. nativeParams: options
  20417. });
  20418. return this;
  20419. };
  20420. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20421. // Collisions
  20422. /**
  20423. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20424. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20425. */
  20426. get: function () {
  20427. return this._checkCollisions;
  20428. },
  20429. set: function (collisionEnabled) {
  20430. this._checkCollisions = collisionEnabled;
  20431. if (this.getScene().workerCollisions) {
  20432. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20433. }
  20434. },
  20435. enumerable: true,
  20436. configurable: true
  20437. });
  20438. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20439. /**
  20440. * Gets Collider object used to compute collisions (not physics)
  20441. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20442. */
  20443. get: function () {
  20444. return this._collider;
  20445. },
  20446. enumerable: true,
  20447. configurable: true
  20448. });
  20449. /**
  20450. * Move the mesh using collision engine
  20451. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20452. * @param displacement defines the requested displacement vector
  20453. * @returns the current mesh
  20454. */
  20455. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20456. var globalPosition = this.getAbsolutePosition();
  20457. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20458. if (!this._collider) {
  20459. this._collider = new BABYLON.Collider();
  20460. }
  20461. this._collider._radius = this.ellipsoid;
  20462. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20463. return this;
  20464. };
  20465. // Submeshes octree
  20466. /**
  20467. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20468. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20469. * @param maxCapacity defines the maximum size of each block (64 by default)
  20470. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20471. * @returns the new octree
  20472. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20473. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20474. */
  20475. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20476. if (maxCapacity === void 0) { maxCapacity = 64; }
  20477. if (maxDepth === void 0) { maxDepth = 2; }
  20478. if (!this._submeshesOctree) {
  20479. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20480. }
  20481. this.computeWorldMatrix(true);
  20482. var boundingInfo = this.getBoundingInfo();
  20483. // Update octree
  20484. var bbox = boundingInfo.boundingBox;
  20485. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20486. return this._submeshesOctree;
  20487. };
  20488. // Collisions
  20489. /** @hidden */
  20490. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20491. this._generatePointsArray();
  20492. if (!this._positions) {
  20493. return this;
  20494. }
  20495. // Transformation
  20496. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20497. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20498. subMesh._lastColliderWorldVertices = [];
  20499. subMesh._trianglePlanes = [];
  20500. var start = subMesh.verticesStart;
  20501. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20502. for (var i = start; i < end; i++) {
  20503. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20504. }
  20505. }
  20506. // Collide
  20507. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20508. if (collider.collisionFound) {
  20509. collider.collidedMesh = this;
  20510. }
  20511. return this;
  20512. };
  20513. /** @hidden */
  20514. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20515. var subMeshes;
  20516. var len;
  20517. // Octrees
  20518. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20519. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20520. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20521. len = intersections.length;
  20522. subMeshes = intersections.data;
  20523. }
  20524. else {
  20525. subMeshes = this.subMeshes;
  20526. len = subMeshes.length;
  20527. }
  20528. for (var index = 0; index < len; index++) {
  20529. var subMesh = subMeshes[index];
  20530. // Bounding test
  20531. if (len > 1 && !subMesh._checkCollision(collider))
  20532. continue;
  20533. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20534. }
  20535. return this;
  20536. };
  20537. /** @hidden */
  20538. AbstractMesh.prototype._checkCollision = function (collider) {
  20539. // Bounding box test
  20540. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20541. return this;
  20542. // Transformation matrix
  20543. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20544. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20545. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20546. return this;
  20547. };
  20548. // Picking
  20549. /** @hidden */
  20550. AbstractMesh.prototype._generatePointsArray = function () {
  20551. return false;
  20552. };
  20553. /**
  20554. * Checks if the passed Ray intersects with the mesh
  20555. * @param ray defines the ray to use
  20556. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20557. * @returns the picking info
  20558. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20559. */
  20560. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20561. var pickingInfo = new BABYLON.PickingInfo();
  20562. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20563. return pickingInfo;
  20564. }
  20565. if (!this._generatePointsArray()) {
  20566. return pickingInfo;
  20567. }
  20568. var intersectInfo = null;
  20569. // Octrees
  20570. var subMeshes;
  20571. var len;
  20572. if (this._submeshesOctree && this.useOctreeForPicking) {
  20573. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20574. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20575. len = intersections.length;
  20576. subMeshes = intersections.data;
  20577. }
  20578. else {
  20579. subMeshes = this.subMeshes;
  20580. len = subMeshes.length;
  20581. }
  20582. for (var index = 0; index < len; index++) {
  20583. var subMesh = subMeshes[index];
  20584. // Bounding test
  20585. if (len > 1 && !subMesh.canIntersects(ray))
  20586. continue;
  20587. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20588. if (currentIntersectInfo) {
  20589. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20590. intersectInfo = currentIntersectInfo;
  20591. intersectInfo.subMeshId = index;
  20592. if (fastCheck) {
  20593. break;
  20594. }
  20595. }
  20596. }
  20597. }
  20598. if (intersectInfo) {
  20599. // Get picked point
  20600. var world = this.getWorldMatrix();
  20601. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20602. var direction = ray.direction.clone();
  20603. direction = direction.scale(intersectInfo.distance);
  20604. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20605. var pickedPoint = worldOrigin.add(worldDirection);
  20606. // Return result
  20607. pickingInfo.hit = true;
  20608. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20609. pickingInfo.pickedPoint = pickedPoint;
  20610. pickingInfo.pickedMesh = this;
  20611. pickingInfo.bu = intersectInfo.bu || 0;
  20612. pickingInfo.bv = intersectInfo.bv || 0;
  20613. pickingInfo.faceId = intersectInfo.faceId;
  20614. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20615. return pickingInfo;
  20616. }
  20617. return pickingInfo;
  20618. };
  20619. /**
  20620. * Clones the current mesh
  20621. * @param name defines the mesh name
  20622. * @param newParent defines the new mesh parent
  20623. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20624. * @returns the new mesh
  20625. */
  20626. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20627. return null;
  20628. };
  20629. /**
  20630. * Disposes all the submeshes of the current meshnp
  20631. * @returns the current mesh
  20632. */
  20633. AbstractMesh.prototype.releaseSubMeshes = function () {
  20634. if (this.subMeshes) {
  20635. while (this.subMeshes.length) {
  20636. this.subMeshes[0].dispose();
  20637. }
  20638. }
  20639. else {
  20640. this.subMeshes = new Array();
  20641. }
  20642. return this;
  20643. };
  20644. /**
  20645. * Releases resources associated with this abstract mesh.
  20646. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20647. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20648. */
  20649. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20650. var _this = this;
  20651. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20652. var index;
  20653. // Smart Array Retainers.
  20654. this.getScene().freeActiveMeshes();
  20655. this.getScene().freeRenderingGroups();
  20656. // Action manager
  20657. if (this.actionManager !== undefined && this.actionManager !== null) {
  20658. this.actionManager.dispose();
  20659. this.actionManager = null;
  20660. }
  20661. // Skeleton
  20662. this._skeleton = null;
  20663. // Physics
  20664. if (this.physicsImpostor) {
  20665. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20666. }
  20667. // Intersections in progress
  20668. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20669. var other = this._intersectionsInProgress[index];
  20670. var pos = other._intersectionsInProgress.indexOf(this);
  20671. other._intersectionsInProgress.splice(pos, 1);
  20672. }
  20673. this._intersectionsInProgress = [];
  20674. // Lights
  20675. var lights = this.getScene().lights;
  20676. lights.forEach(function (light) {
  20677. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20678. if (meshIndex !== -1) {
  20679. light.includedOnlyMeshes.splice(meshIndex, 1);
  20680. }
  20681. meshIndex = light.excludedMeshes.indexOf(_this);
  20682. if (meshIndex !== -1) {
  20683. light.excludedMeshes.splice(meshIndex, 1);
  20684. }
  20685. // Shadow generators
  20686. var generator = light.getShadowGenerator();
  20687. if (generator) {
  20688. var shadowMap = generator.getShadowMap();
  20689. if (shadowMap && shadowMap.renderList) {
  20690. meshIndex = shadowMap.renderList.indexOf(_this);
  20691. if (meshIndex !== -1) {
  20692. shadowMap.renderList.splice(meshIndex, 1);
  20693. }
  20694. }
  20695. }
  20696. });
  20697. // Edges
  20698. if (this._edgesRenderer) {
  20699. this._edgesRenderer.dispose();
  20700. this._edgesRenderer = null;
  20701. }
  20702. // SubMeshes
  20703. if (this.getClassName() !== "InstancedMesh") {
  20704. this.releaseSubMeshes();
  20705. }
  20706. // Octree
  20707. var sceneOctree = this.getScene().selectionOctree;
  20708. if (sceneOctree !== undefined && sceneOctree !== null) {
  20709. var index = sceneOctree.dynamicContent.indexOf(this);
  20710. if (index !== -1) {
  20711. sceneOctree.dynamicContent.splice(index, 1);
  20712. }
  20713. }
  20714. // Query
  20715. var engine = this.getScene().getEngine();
  20716. if (this._occlusionQuery) {
  20717. this._isOcclusionQueryInProgress = false;
  20718. engine.deleteQuery(this._occlusionQuery);
  20719. this._occlusionQuery = null;
  20720. }
  20721. // Engine
  20722. engine.wipeCaches();
  20723. // Remove from scene
  20724. this.getScene().removeMesh(this);
  20725. if (disposeMaterialAndTextures) {
  20726. if (this.material) {
  20727. this.material.dispose(false, true);
  20728. }
  20729. }
  20730. if (!doNotRecurse) {
  20731. // Particles
  20732. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20733. if (this.getScene().particleSystems[index].emitter === this) {
  20734. this.getScene().particleSystems[index].dispose();
  20735. index--;
  20736. }
  20737. }
  20738. }
  20739. // facet data
  20740. if (this._facetDataEnabled) {
  20741. this.disableFacetData();
  20742. }
  20743. this.onAfterWorldMatrixUpdateObservable.clear();
  20744. this.onCollideObservable.clear();
  20745. this.onCollisionPositionChangeObservable.clear();
  20746. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20747. };
  20748. /**
  20749. * Adds the passed mesh as a child to the current mesh
  20750. * @param mesh defines the child mesh
  20751. * @returns the current mesh
  20752. */
  20753. AbstractMesh.prototype.addChild = function (mesh) {
  20754. mesh.setParent(this);
  20755. return this;
  20756. };
  20757. /**
  20758. * Removes the passed mesh from the current mesh children list
  20759. * @param mesh defines the child mesh
  20760. * @returns the current mesh
  20761. */
  20762. AbstractMesh.prototype.removeChild = function (mesh) {
  20763. mesh.setParent(null);
  20764. return this;
  20765. };
  20766. // Facet data
  20767. /** @hidden */
  20768. AbstractMesh.prototype._initFacetData = function () {
  20769. if (!this._facetNormals) {
  20770. this._facetNormals = new Array();
  20771. }
  20772. if (!this._facetPositions) {
  20773. this._facetPositions = new Array();
  20774. }
  20775. if (!this._facetPartitioning) {
  20776. this._facetPartitioning = new Array();
  20777. }
  20778. this._facetNb = (this.getIndices().length / 3) | 0;
  20779. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20780. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20781. for (var f = 0; f < this._facetNb; f++) {
  20782. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20783. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20784. }
  20785. this._facetDataEnabled = true;
  20786. return this;
  20787. };
  20788. /**
  20789. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20790. * This method can be called within the render loop.
  20791. * 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
  20792. * @returns the current mesh
  20793. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20794. */
  20795. AbstractMesh.prototype.updateFacetData = function () {
  20796. if (!this._facetDataEnabled) {
  20797. this._initFacetData();
  20798. }
  20799. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20800. var indices = this.getIndices();
  20801. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20802. var bInfo = this.getBoundingInfo();
  20803. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20804. // init arrays, matrix and sort function on first call
  20805. this._facetDepthSortEnabled = true;
  20806. if (indices instanceof Uint16Array) {
  20807. this._depthSortedIndices = new Uint16Array(indices);
  20808. }
  20809. else if (indices instanceof Uint32Array) {
  20810. this._depthSortedIndices = new Uint32Array(indices);
  20811. }
  20812. else {
  20813. var needs32bits = false;
  20814. for (var i = 0; i < indices.length; i++) {
  20815. if (indices[i] > 65535) {
  20816. needs32bits = true;
  20817. break;
  20818. }
  20819. }
  20820. if (needs32bits) {
  20821. this._depthSortedIndices = new Uint32Array(indices);
  20822. }
  20823. else {
  20824. this._depthSortedIndices = new Uint16Array(indices);
  20825. }
  20826. }
  20827. this._facetDepthSortFunction = function (f1, f2) {
  20828. return (f2.sqDistance - f1.sqDistance);
  20829. };
  20830. if (!this._facetDepthSortFrom) {
  20831. var camera = this.getScene().activeCamera;
  20832. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20833. }
  20834. this._depthSortedFacets = [];
  20835. for (var f = 0; f < this._facetNb; f++) {
  20836. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20837. this._depthSortedFacets.push(depthSortedFacet);
  20838. }
  20839. this._invertedMatrix = BABYLON.Matrix.Identity();
  20840. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20841. }
  20842. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20843. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20844. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20845. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20846. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20847. this._subDiv.max = this._partitioningSubdivisions;
  20848. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20849. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20850. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20851. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20852. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20853. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20854. // set the parameters for ComputeNormals()
  20855. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20856. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20857. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20858. this._facetParameters.bInfo = bInfo;
  20859. this._facetParameters.bbSize = this._bbSize;
  20860. this._facetParameters.subDiv = this._subDiv;
  20861. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20862. this._facetParameters.depthSort = this._facetDepthSort;
  20863. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20864. this.computeWorldMatrix(true);
  20865. this._worldMatrix.invertToRef(this._invertedMatrix);
  20866. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20867. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20868. }
  20869. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20870. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20871. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20872. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20873. var l = (this._depthSortedIndices.length / 3) | 0;
  20874. for (var f = 0; f < l; f++) {
  20875. var sind = this._depthSortedFacets[f].ind;
  20876. this._depthSortedIndices[f * 3] = indices[sind];
  20877. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20878. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20879. }
  20880. this.updateIndices(this._depthSortedIndices);
  20881. }
  20882. return this;
  20883. };
  20884. /**
  20885. * Returns the facetLocalNormals array.
  20886. * The normals are expressed in the mesh local spac
  20887. * @returns an array of Vector3
  20888. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20889. */
  20890. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20891. if (!this._facetNormals) {
  20892. this.updateFacetData();
  20893. }
  20894. return this._facetNormals;
  20895. };
  20896. /**
  20897. * Returns the facetLocalPositions array.
  20898. * The facet positions are expressed in the mesh local space
  20899. * @returns an array of Vector3
  20900. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20901. */
  20902. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20903. if (!this._facetPositions) {
  20904. this.updateFacetData();
  20905. }
  20906. return this._facetPositions;
  20907. };
  20908. /**
  20909. * Returns the facetLocalPartioning array
  20910. * @returns an array of array of numbers
  20911. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20912. */
  20913. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20914. if (!this._facetPartitioning) {
  20915. this.updateFacetData();
  20916. }
  20917. return this._facetPartitioning;
  20918. };
  20919. /**
  20920. * Returns the i-th facet position in the world system.
  20921. * This method allocates a new Vector3 per call
  20922. * @param i defines the facet index
  20923. * @returns a new Vector3
  20924. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20925. */
  20926. AbstractMesh.prototype.getFacetPosition = function (i) {
  20927. var pos = BABYLON.Vector3.Zero();
  20928. this.getFacetPositionToRef(i, pos);
  20929. return pos;
  20930. };
  20931. /**
  20932. * Sets the reference Vector3 with the i-th facet position in the world system
  20933. * @param i defines the facet index
  20934. * @param ref defines the target vector
  20935. * @returns the current mesh
  20936. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20937. */
  20938. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20939. var localPos = (this.getFacetLocalPositions())[i];
  20940. var world = this.getWorldMatrix();
  20941. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20942. return this;
  20943. };
  20944. /**
  20945. * Returns the i-th facet normal in the world system.
  20946. * This method allocates a new Vector3 per call
  20947. * @param i defines the facet index
  20948. * @returns a new Vector3
  20949. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20950. */
  20951. AbstractMesh.prototype.getFacetNormal = function (i) {
  20952. var norm = BABYLON.Vector3.Zero();
  20953. this.getFacetNormalToRef(i, norm);
  20954. return norm;
  20955. };
  20956. /**
  20957. * Sets the reference Vector3 with the i-th facet normal in the world system
  20958. * @param i defines the facet index
  20959. * @param ref defines the target vector
  20960. * @returns the current mesh
  20961. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20962. */
  20963. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20964. var localNorm = (this.getFacetLocalNormals())[i];
  20965. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20966. return this;
  20967. };
  20968. /**
  20969. * 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)
  20970. * @param x defines x coordinate
  20971. * @param y defines y coordinate
  20972. * @param z defines z coordinate
  20973. * @returns the array of facet indexes
  20974. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20975. */
  20976. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20977. var bInfo = this.getBoundingInfo();
  20978. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20979. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20980. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20981. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20982. return null;
  20983. }
  20984. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20985. };
  20986. /**
  20987. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20988. * @param projected sets as the (x,y,z) world projection on the facet
  20989. * @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
  20990. * @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
  20991. * @param x defines x coordinate
  20992. * @param y defines y coordinate
  20993. * @param z defines z coordinate
  20994. * @returns the face index if found (or null instead)
  20995. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20996. */
  20997. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20998. if (checkFace === void 0) { checkFace = false; }
  20999. if (facing === void 0) { facing = true; }
  21000. var world = this.getWorldMatrix();
  21001. var invMat = BABYLON.Tmp.Matrix[5];
  21002. world.invertToRef(invMat);
  21003. var invVect = BABYLON.Tmp.Vector3[8];
  21004. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21005. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21006. if (projected) {
  21007. // tranform the local computed projected vector to world coordinates
  21008. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21009. }
  21010. return closest;
  21011. };
  21012. /**
  21013. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21014. * @param projected sets as the (x,y,z) local projection on the facet
  21015. * @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
  21016. * @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
  21017. * @param x defines x coordinate
  21018. * @param y defines y coordinate
  21019. * @param z defines z coordinate
  21020. * @returns the face index if found (or null instead)
  21021. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21022. */
  21023. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21024. if (checkFace === void 0) { checkFace = false; }
  21025. if (facing === void 0) { facing = true; }
  21026. var closest = null;
  21027. var tmpx = 0.0;
  21028. var tmpy = 0.0;
  21029. var tmpz = 0.0;
  21030. var d = 0.0; // tmp dot facet normal * facet position
  21031. var t0 = 0.0;
  21032. var projx = 0.0;
  21033. var projy = 0.0;
  21034. var projz = 0.0;
  21035. // Get all the facets in the same partitioning block than (x, y, z)
  21036. var facetPositions = this.getFacetLocalPositions();
  21037. var facetNormals = this.getFacetLocalNormals();
  21038. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21039. if (!facetsInBlock) {
  21040. return null;
  21041. }
  21042. // Get the closest facet to (x, y, z)
  21043. var shortest = Number.MAX_VALUE; // init distance vars
  21044. var tmpDistance = shortest;
  21045. var fib; // current facet in the block
  21046. var norm; // current facet normal
  21047. var p0; // current facet barycenter position
  21048. // loop on all the facets in the current partitioning block
  21049. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21050. fib = facetsInBlock[idx];
  21051. norm = facetNormals[fib];
  21052. p0 = facetPositions[fib];
  21053. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21054. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21055. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21056. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21057. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21058. projx = x + norm.x * t0;
  21059. projy = y + norm.y * t0;
  21060. projz = z + norm.z * t0;
  21061. tmpx = projx - x;
  21062. tmpy = projy - y;
  21063. tmpz = projz - z;
  21064. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21065. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21066. shortest = tmpDistance;
  21067. closest = fib;
  21068. if (projected) {
  21069. projected.x = projx;
  21070. projected.y = projy;
  21071. projected.z = projz;
  21072. }
  21073. }
  21074. }
  21075. }
  21076. return closest;
  21077. };
  21078. /**
  21079. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21080. * @returns the parameters
  21081. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21082. */
  21083. AbstractMesh.prototype.getFacetDataParameters = function () {
  21084. return this._facetParameters;
  21085. };
  21086. /**
  21087. * Disables the feature FacetData and frees the related memory
  21088. * @returns the current mesh
  21089. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21090. */
  21091. AbstractMesh.prototype.disableFacetData = function () {
  21092. if (this._facetDataEnabled) {
  21093. this._facetDataEnabled = false;
  21094. this._facetPositions = new Array();
  21095. this._facetNormals = new Array();
  21096. this._facetPartitioning = new Array();
  21097. this._facetParameters = null;
  21098. this._depthSortedIndices = new Uint32Array(0);
  21099. }
  21100. return this;
  21101. };
  21102. /**
  21103. * Updates the AbstractMesh indices array
  21104. * @param indices defines the data source
  21105. * @returns the current mesh
  21106. */
  21107. AbstractMesh.prototype.updateIndices = function (indices) {
  21108. return this;
  21109. };
  21110. /**
  21111. * Creates new normals data for the mesh
  21112. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21113. * @returns the current mesh
  21114. */
  21115. AbstractMesh.prototype.createNormals = function (updatable) {
  21116. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21117. var indices = this.getIndices();
  21118. var normals;
  21119. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21120. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21121. }
  21122. else {
  21123. normals = [];
  21124. }
  21125. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21126. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21127. return this;
  21128. };
  21129. /**
  21130. * Align the mesh with a normal
  21131. * @param normal defines the normal to use
  21132. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21133. * @returns the current mesh
  21134. */
  21135. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21136. if (!upDirection) {
  21137. upDirection = BABYLON.Axis.Y;
  21138. }
  21139. var axisX = BABYLON.Tmp.Vector3[0];
  21140. var axisZ = BABYLON.Tmp.Vector3[1];
  21141. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21142. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21143. if (this.rotationQuaternion) {
  21144. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21145. }
  21146. else {
  21147. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21148. }
  21149. return this;
  21150. };
  21151. /** @hidden */
  21152. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21153. this._isOccluded = false;
  21154. };
  21155. /** No occlusion */
  21156. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21157. /** Occlusion set to optimisitic */
  21158. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21159. /** Occlusion set to strict */
  21160. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21161. /** Use an accurante occlusion algorithm */
  21162. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21163. /** Use a conservative occlusion algorithm */
  21164. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21165. return AbstractMesh;
  21166. }(BABYLON.TransformNode));
  21167. BABYLON.AbstractMesh = AbstractMesh;
  21168. })(BABYLON || (BABYLON = {}));
  21169. //# sourceMappingURL=babylon.abstractMesh.js.map
  21170. var BABYLON;
  21171. (function (BABYLON) {
  21172. /**
  21173. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21174. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21175. * 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.
  21176. */
  21177. var Light = /** @class */ (function (_super) {
  21178. __extends(Light, _super);
  21179. /**
  21180. * Creates a Light object in the scene.
  21181. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21182. * @param name The firendly name of the light
  21183. * @param scene The scene the light belongs too
  21184. */
  21185. function Light(name, scene) {
  21186. var _this = _super.call(this, name, scene) || this;
  21187. /**
  21188. * Diffuse gives the basic color to an object.
  21189. */
  21190. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21191. /**
  21192. * Specular produces a highlight color on an object.
  21193. * Note: This is note affecting PBR materials.
  21194. */
  21195. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21196. /**
  21197. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21198. * falling off base on range or angle.
  21199. * This can be set to any values in Light.FALLOFF_x.
  21200. *
  21201. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21202. * other types of materials.
  21203. */
  21204. _this.falloffType = Light.FALLOFF_DEFAULT;
  21205. /**
  21206. * Strength of the light.
  21207. * Note: By default it is define in the framework own unit.
  21208. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21209. */
  21210. _this.intensity = 1.0;
  21211. _this._range = Number.MAX_VALUE;
  21212. _this._inverseSquaredRange = 0;
  21213. /**
  21214. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21215. * of light.
  21216. */
  21217. _this._photometricScale = 1.0;
  21218. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21219. _this._radius = 0.00001;
  21220. /**
  21221. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21222. * exceeding the number allowed of the materials.
  21223. */
  21224. _this.renderPriority = 0;
  21225. _this._shadowEnabled = true;
  21226. _this._excludeWithLayerMask = 0;
  21227. _this._includeOnlyWithLayerMask = 0;
  21228. _this._lightmapMode = 0;
  21229. /**
  21230. * @hidden Internal use only.
  21231. */
  21232. _this._excludedMeshesIds = new Array();
  21233. /**
  21234. * @hidden Internal use only.
  21235. */
  21236. _this._includedOnlyMeshesIds = new Array();
  21237. _this.getScene().addLight(_this);
  21238. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21239. _this._buildUniformLayout();
  21240. _this.includedOnlyMeshes = new Array();
  21241. _this.excludedMeshes = new Array();
  21242. _this._resyncMeshes();
  21243. return _this;
  21244. }
  21245. Object.defineProperty(Light.prototype, "range", {
  21246. /**
  21247. * Defines how far from the source the light is impacting in scene units.
  21248. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21249. */
  21250. get: function () {
  21251. return this._range;
  21252. },
  21253. /**
  21254. * Defines how far from the source the light is impacting in scene units.
  21255. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21256. */
  21257. set: function (value) {
  21258. this._range = value;
  21259. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. Object.defineProperty(Light.prototype, "intensityMode", {
  21265. /**
  21266. * Gets the photometric scale used to interpret the intensity.
  21267. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21268. */
  21269. get: function () {
  21270. return this._intensityMode;
  21271. },
  21272. /**
  21273. * Sets the photometric scale used to interpret the intensity.
  21274. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21275. */
  21276. set: function (value) {
  21277. this._intensityMode = value;
  21278. this._computePhotometricScale();
  21279. },
  21280. enumerable: true,
  21281. configurable: true
  21282. });
  21283. ;
  21284. ;
  21285. Object.defineProperty(Light.prototype, "radius", {
  21286. /**
  21287. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21288. */
  21289. get: function () {
  21290. return this._radius;
  21291. },
  21292. /**
  21293. * sets the light radius used by PBR Materials to simulate soft area lights.
  21294. */
  21295. set: function (value) {
  21296. this._radius = value;
  21297. this._computePhotometricScale();
  21298. },
  21299. enumerable: true,
  21300. configurable: true
  21301. });
  21302. ;
  21303. ;
  21304. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21305. /**
  21306. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21307. * the current shadow generator.
  21308. */
  21309. get: function () {
  21310. return this._shadowEnabled;
  21311. },
  21312. /**
  21313. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21314. * the current shadow generator.
  21315. */
  21316. set: function (value) {
  21317. if (this._shadowEnabled === value) {
  21318. return;
  21319. }
  21320. this._shadowEnabled = value;
  21321. this._markMeshesAsLightDirty();
  21322. },
  21323. enumerable: true,
  21324. configurable: true
  21325. });
  21326. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21327. /**
  21328. * Gets the only meshes impacted by this light.
  21329. */
  21330. get: function () {
  21331. return this._includedOnlyMeshes;
  21332. },
  21333. /**
  21334. * Sets the only meshes impacted by this light.
  21335. */
  21336. set: function (value) {
  21337. this._includedOnlyMeshes = value;
  21338. this._hookArrayForIncludedOnly(value);
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21344. /**
  21345. * Gets the meshes not impacted by this light.
  21346. */
  21347. get: function () {
  21348. return this._excludedMeshes;
  21349. },
  21350. /**
  21351. * Sets the meshes not impacted by this light.
  21352. */
  21353. set: function (value) {
  21354. this._excludedMeshes = value;
  21355. this._hookArrayForExcluded(value);
  21356. },
  21357. enumerable: true,
  21358. configurable: true
  21359. });
  21360. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21361. /**
  21362. * Gets the layer id use to find what meshes are not impacted by the light.
  21363. * Inactive if 0
  21364. */
  21365. get: function () {
  21366. return this._excludeWithLayerMask;
  21367. },
  21368. /**
  21369. * Sets the layer id use to find what meshes are not impacted by the light.
  21370. * Inactive if 0
  21371. */
  21372. set: function (value) {
  21373. this._excludeWithLayerMask = value;
  21374. this._resyncMeshes();
  21375. },
  21376. enumerable: true,
  21377. configurable: true
  21378. });
  21379. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21380. /**
  21381. * Gets the layer id use to find what meshes are impacted by the light.
  21382. * Inactive if 0
  21383. */
  21384. get: function () {
  21385. return this._includeOnlyWithLayerMask;
  21386. },
  21387. /**
  21388. * Sets the layer id use to find what meshes are impacted by the light.
  21389. * Inactive if 0
  21390. */
  21391. set: function (value) {
  21392. this._includeOnlyWithLayerMask = value;
  21393. this._resyncMeshes();
  21394. },
  21395. enumerable: true,
  21396. configurable: true
  21397. });
  21398. Object.defineProperty(Light.prototype, "lightmapMode", {
  21399. /**
  21400. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21401. */
  21402. get: function () {
  21403. return this._lightmapMode;
  21404. },
  21405. /**
  21406. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21407. */
  21408. set: function (value) {
  21409. if (this._lightmapMode === value) {
  21410. return;
  21411. }
  21412. this._lightmapMode = value;
  21413. this._markMeshesAsLightDirty();
  21414. },
  21415. enumerable: true,
  21416. configurable: true
  21417. });
  21418. /**
  21419. * Returns the string "Light".
  21420. * @returns the class name
  21421. */
  21422. Light.prototype.getClassName = function () {
  21423. return "Light";
  21424. };
  21425. /**
  21426. * Converts the light information to a readable string for debug purpose.
  21427. * @param fullDetails Supports for multiple levels of logging within scene loading
  21428. * @returns the human readable light info
  21429. */
  21430. Light.prototype.toString = function (fullDetails) {
  21431. var ret = "Name: " + this.name;
  21432. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21433. if (this.animations) {
  21434. for (var i = 0; i < this.animations.length; i++) {
  21435. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21436. }
  21437. }
  21438. if (fullDetails) {
  21439. }
  21440. return ret;
  21441. };
  21442. /**
  21443. * Set the enabled state of this node.
  21444. * @param value - the new enabled state
  21445. */
  21446. Light.prototype.setEnabled = function (value) {
  21447. _super.prototype.setEnabled.call(this, value);
  21448. this._resyncMeshes();
  21449. };
  21450. /**
  21451. * Returns the Light associated shadow generator if any.
  21452. * @return the associated shadow generator.
  21453. */
  21454. Light.prototype.getShadowGenerator = function () {
  21455. return this._shadowGenerator;
  21456. };
  21457. /**
  21458. * Returns a Vector3, the absolute light position in the World.
  21459. * @returns the world space position of the light
  21460. */
  21461. Light.prototype.getAbsolutePosition = function () {
  21462. return BABYLON.Vector3.Zero();
  21463. };
  21464. /**
  21465. * Specifies if the light will affect the passed mesh.
  21466. * @param mesh The mesh to test against the light
  21467. * @return true the mesh is affected otherwise, false.
  21468. */
  21469. Light.prototype.canAffectMesh = function (mesh) {
  21470. if (!mesh) {
  21471. return true;
  21472. }
  21473. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21474. return false;
  21475. }
  21476. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21477. return false;
  21478. }
  21479. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21480. return false;
  21481. }
  21482. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21483. return false;
  21484. }
  21485. return true;
  21486. };
  21487. /**
  21488. * Computes and Returns the light World matrix.
  21489. * @returns the world matrix
  21490. */
  21491. Light.prototype.getWorldMatrix = function () {
  21492. this._currentRenderId = this.getScene().getRenderId();
  21493. this._childRenderId = this._currentRenderId;
  21494. var worldMatrix = this._getWorldMatrix();
  21495. if (this.parent && this.parent.getWorldMatrix) {
  21496. if (!this._parentedWorldMatrix) {
  21497. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21498. }
  21499. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21500. this._markSyncedWithParent();
  21501. return this._parentedWorldMatrix;
  21502. }
  21503. return worldMatrix;
  21504. };
  21505. /**
  21506. * Sort function to order lights for rendering.
  21507. * @param a First Light object to compare to second.
  21508. * @param b Second Light object to compare first.
  21509. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21510. */
  21511. Light.CompareLightsPriority = function (a, b) {
  21512. //shadow-casting lights have priority over non-shadow-casting lights
  21513. //the renderPrioirty is a secondary sort criterion
  21514. if (a.shadowEnabled !== b.shadowEnabled) {
  21515. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21516. }
  21517. return b.renderPriority - a.renderPriority;
  21518. };
  21519. /**
  21520. * Releases resources associated with this node.
  21521. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21522. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21523. */
  21524. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21525. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21526. if (this._shadowGenerator) {
  21527. this._shadowGenerator.dispose();
  21528. this._shadowGenerator = null;
  21529. }
  21530. // Animations
  21531. this.getScene().stopAnimation(this);
  21532. // Remove from meshes
  21533. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21534. var mesh = _a[_i];
  21535. mesh._removeLightSource(this);
  21536. }
  21537. this._uniformBuffer.dispose();
  21538. // Remove from scene
  21539. this.getScene().removeLight(this);
  21540. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21541. };
  21542. /**
  21543. * Returns the light type ID (integer).
  21544. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21545. */
  21546. Light.prototype.getTypeID = function () {
  21547. return 0;
  21548. };
  21549. /**
  21550. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21551. * @returns the scaled intensity in intensity mode unit
  21552. */
  21553. Light.prototype.getScaledIntensity = function () {
  21554. return this._photometricScale * this.intensity;
  21555. };
  21556. /**
  21557. * Returns a new Light object, named "name", from the current one.
  21558. * @param name The name of the cloned light
  21559. * @returns the new created light
  21560. */
  21561. Light.prototype.clone = function (name) {
  21562. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21563. if (!constructor) {
  21564. return null;
  21565. }
  21566. return BABYLON.SerializationHelper.Clone(constructor, this);
  21567. };
  21568. /**
  21569. * Serializes the current light into a Serialization object.
  21570. * @returns the serialized object.
  21571. */
  21572. Light.prototype.serialize = function () {
  21573. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21574. // Type
  21575. serializationObject.type = this.getTypeID();
  21576. // Parent
  21577. if (this.parent) {
  21578. serializationObject.parentId = this.parent.id;
  21579. }
  21580. // Inclusion / exclusions
  21581. if (this.excludedMeshes.length > 0) {
  21582. serializationObject.excludedMeshesIds = [];
  21583. this.excludedMeshes.forEach(function (mesh) {
  21584. serializationObject.excludedMeshesIds.push(mesh.id);
  21585. });
  21586. }
  21587. if (this.includedOnlyMeshes.length > 0) {
  21588. serializationObject.includedOnlyMeshesIds = [];
  21589. this.includedOnlyMeshes.forEach(function (mesh) {
  21590. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21591. });
  21592. }
  21593. // Animations
  21594. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21595. serializationObject.ranges = this.serializeAnimationRanges();
  21596. return serializationObject;
  21597. };
  21598. /**
  21599. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21600. * This new light is named "name" and added to the passed scene.
  21601. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21602. * @param name The friendly name of the light
  21603. * @param scene The scene the new light will belong to
  21604. * @returns the constructor function
  21605. */
  21606. Light.GetConstructorFromName = function (type, name, scene) {
  21607. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21608. if (constructorFunc) {
  21609. return constructorFunc;
  21610. }
  21611. // Default to no light for none present once.
  21612. return null;
  21613. };
  21614. /**
  21615. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21616. * @param parsedLight The JSON representation of the light
  21617. * @param scene The scene to create the parsed light in
  21618. * @returns the created light after parsing
  21619. */
  21620. Light.Parse = function (parsedLight, scene) {
  21621. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21622. if (!constructor) {
  21623. return null;
  21624. }
  21625. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21626. // Inclusion / exclusions
  21627. if (parsedLight.excludedMeshesIds) {
  21628. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21629. }
  21630. if (parsedLight.includedOnlyMeshesIds) {
  21631. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21632. }
  21633. // Parent
  21634. if (parsedLight.parentId) {
  21635. light._waitingParentId = parsedLight.parentId;
  21636. }
  21637. // Animations
  21638. if (parsedLight.animations) {
  21639. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21640. var parsedAnimation = parsedLight.animations[animationIndex];
  21641. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21642. }
  21643. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21644. }
  21645. if (parsedLight.autoAnimate) {
  21646. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21647. }
  21648. return light;
  21649. };
  21650. Light.prototype._hookArrayForExcluded = function (array) {
  21651. var _this = this;
  21652. var oldPush = array.push;
  21653. array.push = function () {
  21654. var items = [];
  21655. for (var _i = 0; _i < arguments.length; _i++) {
  21656. items[_i] = arguments[_i];
  21657. }
  21658. var result = oldPush.apply(array, items);
  21659. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21660. var item = items_1[_a];
  21661. item._resyncLighSource(_this);
  21662. }
  21663. return result;
  21664. };
  21665. var oldSplice = array.splice;
  21666. array.splice = function (index, deleteCount) {
  21667. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21668. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21669. var item = deleted_1[_i];
  21670. item._resyncLighSource(_this);
  21671. }
  21672. return deleted;
  21673. };
  21674. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21675. var item = array_1[_i];
  21676. item._resyncLighSource(this);
  21677. }
  21678. };
  21679. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21680. var _this = this;
  21681. var oldPush = array.push;
  21682. array.push = function () {
  21683. var items = [];
  21684. for (var _i = 0; _i < arguments.length; _i++) {
  21685. items[_i] = arguments[_i];
  21686. }
  21687. var result = oldPush.apply(array, items);
  21688. _this._resyncMeshes();
  21689. return result;
  21690. };
  21691. var oldSplice = array.splice;
  21692. array.splice = function (index, deleteCount) {
  21693. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21694. _this._resyncMeshes();
  21695. return deleted;
  21696. };
  21697. this._resyncMeshes();
  21698. };
  21699. Light.prototype._resyncMeshes = function () {
  21700. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21701. var mesh = _a[_i];
  21702. mesh._resyncLighSource(this);
  21703. }
  21704. };
  21705. /**
  21706. * Forces the meshes to update their light related information in their rendering used effects
  21707. * @hidden Internal Use Only
  21708. */
  21709. Light.prototype._markMeshesAsLightDirty = function () {
  21710. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21711. var mesh = _a[_i];
  21712. if (mesh._lightSources.indexOf(this) !== -1) {
  21713. mesh._markSubMeshesAsLightDirty();
  21714. }
  21715. }
  21716. };
  21717. /**
  21718. * Recomputes the cached photometric scale if needed.
  21719. */
  21720. Light.prototype._computePhotometricScale = function () {
  21721. this._photometricScale = this._getPhotometricScale();
  21722. this.getScene().resetCachedMaterial();
  21723. };
  21724. /**
  21725. * Returns the Photometric Scale according to the light type and intensity mode.
  21726. */
  21727. Light.prototype._getPhotometricScale = function () {
  21728. var photometricScale = 0.0;
  21729. var lightTypeID = this.getTypeID();
  21730. //get photometric mode
  21731. var photometricMode = this.intensityMode;
  21732. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21733. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21734. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21735. }
  21736. else {
  21737. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21738. }
  21739. }
  21740. //compute photometric scale
  21741. switch (lightTypeID) {
  21742. case Light.LIGHTTYPEID_POINTLIGHT:
  21743. case Light.LIGHTTYPEID_SPOTLIGHT:
  21744. switch (photometricMode) {
  21745. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21746. photometricScale = 1.0 / (4.0 * Math.PI);
  21747. break;
  21748. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21749. photometricScale = 1.0;
  21750. break;
  21751. case Light.INTENSITYMODE_LUMINANCE:
  21752. photometricScale = this.radius * this.radius;
  21753. break;
  21754. }
  21755. break;
  21756. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21757. switch (photometricMode) {
  21758. case Light.INTENSITYMODE_ILLUMINANCE:
  21759. photometricScale = 1.0;
  21760. break;
  21761. case Light.INTENSITYMODE_LUMINANCE:
  21762. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21763. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21764. var apexAngleRadians = this.radius;
  21765. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21766. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21767. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21768. photometricScale = solidAngle;
  21769. break;
  21770. }
  21771. break;
  21772. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21773. // No fall off in hemisperic light.
  21774. photometricScale = 1.0;
  21775. break;
  21776. }
  21777. return photometricScale;
  21778. };
  21779. /**
  21780. * Reorder the light in the scene according to their defined priority.
  21781. * @hidden Internal Use Only
  21782. */
  21783. Light.prototype._reorderLightsInScene = function () {
  21784. var scene = this.getScene();
  21785. if (this._renderPriority != 0) {
  21786. scene.requireLightSorting = true;
  21787. }
  21788. this.getScene().sortLightsByPriority();
  21789. };
  21790. /**
  21791. * Falloff Default: light is falling off following the material specification:
  21792. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  21793. */
  21794. Light.FALLOFF_DEFAULT = 0;
  21795. /**
  21796. * Falloff Physical: light is falling off following the inverse squared distance law.
  21797. */
  21798. Light.FALLOFF_PHYSICAL = 1;
  21799. /**
  21800. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  21801. * to enhance interoperability with other engines.
  21802. */
  21803. Light.FALLOFF_GLTF = 2;
  21804. /**
  21805. * Falloff Standard: light is falling off like in the standard material
  21806. * to enhance interoperability with other materials.
  21807. */
  21808. Light.FALLOFF_STANDARD = 3;
  21809. //lightmapMode Consts
  21810. /**
  21811. * If every light affecting the material is in this lightmapMode,
  21812. * material.lightmapTexture adds or multiplies
  21813. * (depends on material.useLightmapAsShadowmap)
  21814. * after every other light calculations.
  21815. */
  21816. Light.LIGHTMAP_DEFAULT = 0;
  21817. /**
  21818. * material.lightmapTexture as only diffuse lighting from this light
  21819. * adds only specular lighting from this light
  21820. * adds dynamic shadows
  21821. */
  21822. Light.LIGHTMAP_SPECULAR = 1;
  21823. /**
  21824. * material.lightmapTexture as only lighting
  21825. * no light calculation from this light
  21826. * only adds dynamic shadows from this light
  21827. */
  21828. Light.LIGHTMAP_SHADOWSONLY = 2;
  21829. // Intensity Mode Consts
  21830. /**
  21831. * Each light type uses the default quantity according to its type:
  21832. * point/spot lights use luminous intensity
  21833. * directional lights use illuminance
  21834. */
  21835. Light.INTENSITYMODE_AUTOMATIC = 0;
  21836. /**
  21837. * lumen (lm)
  21838. */
  21839. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21840. /**
  21841. * candela (lm/sr)
  21842. */
  21843. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21844. /**
  21845. * lux (lm/m^2)
  21846. */
  21847. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21848. /**
  21849. * nit (cd/m^2)
  21850. */
  21851. Light.INTENSITYMODE_LUMINANCE = 4;
  21852. // Light types ids const.
  21853. /**
  21854. * Light type const id of the point light.
  21855. */
  21856. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21857. /**
  21858. * Light type const id of the directional light.
  21859. */
  21860. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21861. /**
  21862. * Light type const id of the spot light.
  21863. */
  21864. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21865. /**
  21866. * Light type const id of the hemispheric light.
  21867. */
  21868. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21869. __decorate([
  21870. BABYLON.serializeAsColor3()
  21871. ], Light.prototype, "diffuse", void 0);
  21872. __decorate([
  21873. BABYLON.serializeAsColor3()
  21874. ], Light.prototype, "specular", void 0);
  21875. __decorate([
  21876. BABYLON.serialize()
  21877. ], Light.prototype, "falloffType", void 0);
  21878. __decorate([
  21879. BABYLON.serialize()
  21880. ], Light.prototype, "intensity", void 0);
  21881. __decorate([
  21882. BABYLON.serialize()
  21883. ], Light.prototype, "range", null);
  21884. __decorate([
  21885. BABYLON.serialize()
  21886. ], Light.prototype, "intensityMode", null);
  21887. __decorate([
  21888. BABYLON.serialize()
  21889. ], Light.prototype, "radius", null);
  21890. __decorate([
  21891. BABYLON.serialize()
  21892. ], Light.prototype, "_renderPriority", void 0);
  21893. __decorate([
  21894. BABYLON.expandToProperty("_reorderLightsInScene")
  21895. ], Light.prototype, "renderPriority", void 0);
  21896. __decorate([
  21897. BABYLON.serialize("shadowEnabled")
  21898. ], Light.prototype, "_shadowEnabled", void 0);
  21899. __decorate([
  21900. BABYLON.serialize("excludeWithLayerMask")
  21901. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21902. __decorate([
  21903. BABYLON.serialize("includeOnlyWithLayerMask")
  21904. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21905. __decorate([
  21906. BABYLON.serialize("lightmapMode")
  21907. ], Light.prototype, "_lightmapMode", void 0);
  21908. return Light;
  21909. }(BABYLON.Node));
  21910. BABYLON.Light = Light;
  21911. })(BABYLON || (BABYLON = {}));
  21912. //# sourceMappingURL=babylon.light.js.map
  21913. var BABYLON;
  21914. (function (BABYLON) {
  21915. var Camera = /** @class */ (function (_super) {
  21916. __extends(Camera, _super);
  21917. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21918. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21919. var _this = _super.call(this, name, scene) || this;
  21920. /**
  21921. * The vector the camera should consider as up.
  21922. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21923. */
  21924. _this.upVector = BABYLON.Vector3.Up();
  21925. _this.orthoLeft = null;
  21926. _this.orthoRight = null;
  21927. _this.orthoBottom = null;
  21928. _this.orthoTop = null;
  21929. /**
  21930. * FOV is set in Radians. (default is 0.8)
  21931. */
  21932. _this.fov = 0.8;
  21933. _this.minZ = 1;
  21934. _this.maxZ = 10000.0;
  21935. _this.inertia = 0.9;
  21936. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21937. _this.isIntermediate = false;
  21938. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21939. /**
  21940. * Restricts the camera to viewing objects with the same layerMask.
  21941. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21942. */
  21943. _this.layerMask = 0x0FFFFFFF;
  21944. /**
  21945. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21946. */
  21947. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21948. // Camera rig members
  21949. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21950. _this._rigCameras = new Array();
  21951. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21952. _this._skipRendering = false;
  21953. _this.customRenderTargets = new Array();
  21954. // Observables
  21955. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21956. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21957. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21958. _this.onRestoreStateObservable = new BABYLON.Observable();
  21959. // Cache
  21960. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21961. _this._projectionMatrix = new BABYLON.Matrix();
  21962. _this._doNotComputeProjectionMatrix = false;
  21963. _this._worldMatrix = BABYLON.Matrix.Identity();
  21964. _this._postProcesses = new Array();
  21965. _this._transformMatrix = BABYLON.Matrix.Zero();
  21966. _this._activeMeshes = new BABYLON.SmartArray(256);
  21967. _this._globalPosition = BABYLON.Vector3.Zero();
  21968. _this._refreshFrustumPlanes = true;
  21969. _this.getScene().addCamera(_this);
  21970. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21971. _this.getScene().activeCamera = _this;
  21972. }
  21973. _this.position = position;
  21974. return _this;
  21975. }
  21976. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21977. get: function () {
  21978. return Camera._PERSPECTIVE_CAMERA;
  21979. },
  21980. enumerable: true,
  21981. configurable: true
  21982. });
  21983. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21984. get: function () {
  21985. return Camera._ORTHOGRAPHIC_CAMERA;
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21991. /**
  21992. * This is the default FOV mode for perspective cameras.
  21993. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21994. *
  21995. */
  21996. get: function () {
  21997. return Camera._FOVMODE_VERTICAL_FIXED;
  21998. },
  21999. enumerable: true,
  22000. configurable: true
  22001. });
  22002. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22003. /**
  22004. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22005. *
  22006. */
  22007. get: function () {
  22008. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22009. },
  22010. enumerable: true,
  22011. configurable: true
  22012. });
  22013. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22014. get: function () {
  22015. return Camera._RIG_MODE_NONE;
  22016. },
  22017. enumerable: true,
  22018. configurable: true
  22019. });
  22020. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22021. get: function () {
  22022. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22023. },
  22024. enumerable: true,
  22025. configurable: true
  22026. });
  22027. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22028. get: function () {
  22029. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22030. },
  22031. enumerable: true,
  22032. configurable: true
  22033. });
  22034. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22035. get: function () {
  22036. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22037. },
  22038. enumerable: true,
  22039. configurable: true
  22040. });
  22041. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22042. get: function () {
  22043. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22044. },
  22045. enumerable: true,
  22046. configurable: true
  22047. });
  22048. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22049. get: function () {
  22050. return Camera._RIG_MODE_VR;
  22051. },
  22052. enumerable: true,
  22053. configurable: true
  22054. });
  22055. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22056. get: function () {
  22057. return Camera._RIG_MODE_WEBVR;
  22058. },
  22059. enumerable: true,
  22060. configurable: true
  22061. });
  22062. /**
  22063. * Store current camera state (fov, position, etc..)
  22064. */
  22065. Camera.prototype.storeState = function () {
  22066. this._stateStored = true;
  22067. this._storedFov = this.fov;
  22068. return this;
  22069. };
  22070. /**
  22071. * Restores the camera state values if it has been stored. You must call storeState() first
  22072. */
  22073. Camera.prototype._restoreStateValues = function () {
  22074. if (!this._stateStored) {
  22075. return false;
  22076. }
  22077. this.fov = this._storedFov;
  22078. return true;
  22079. };
  22080. /**
  22081. * Restored camera state. You must call storeState() first
  22082. */
  22083. Camera.prototype.restoreState = function () {
  22084. if (this._restoreStateValues()) {
  22085. this.onRestoreStateObservable.notifyObservers(this);
  22086. return true;
  22087. }
  22088. return false;
  22089. };
  22090. Camera.prototype.getClassName = function () {
  22091. return "Camera";
  22092. };
  22093. /**
  22094. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22095. */
  22096. Camera.prototype.toString = function (fullDetails) {
  22097. var ret = "Name: " + this.name;
  22098. ret += ", type: " + this.getClassName();
  22099. if (this.animations) {
  22100. for (var i = 0; i < this.animations.length; i++) {
  22101. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22102. }
  22103. }
  22104. if (fullDetails) {
  22105. }
  22106. return ret;
  22107. };
  22108. Object.defineProperty(Camera.prototype, "globalPosition", {
  22109. get: function () {
  22110. return this._globalPosition;
  22111. },
  22112. enumerable: true,
  22113. configurable: true
  22114. });
  22115. Camera.prototype.getActiveMeshes = function () {
  22116. return this._activeMeshes;
  22117. };
  22118. Camera.prototype.isActiveMesh = function (mesh) {
  22119. return (this._activeMeshes.indexOf(mesh) !== -1);
  22120. };
  22121. /**
  22122. * Is this camera ready to be used/rendered
  22123. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22124. * @return true if the camera is ready
  22125. */
  22126. Camera.prototype.isReady = function (completeCheck) {
  22127. if (completeCheck === void 0) { completeCheck = false; }
  22128. if (completeCheck) {
  22129. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22130. var pp = _a[_i];
  22131. if (pp && !pp.isReady()) {
  22132. return false;
  22133. }
  22134. }
  22135. }
  22136. return _super.prototype.isReady.call(this, completeCheck);
  22137. };
  22138. //Cache
  22139. Camera.prototype._initCache = function () {
  22140. _super.prototype._initCache.call(this);
  22141. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22142. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22143. this._cache.mode = undefined;
  22144. this._cache.minZ = undefined;
  22145. this._cache.maxZ = undefined;
  22146. this._cache.fov = undefined;
  22147. this._cache.fovMode = undefined;
  22148. this._cache.aspectRatio = undefined;
  22149. this._cache.orthoLeft = undefined;
  22150. this._cache.orthoRight = undefined;
  22151. this._cache.orthoBottom = undefined;
  22152. this._cache.orthoTop = undefined;
  22153. this._cache.renderWidth = undefined;
  22154. this._cache.renderHeight = undefined;
  22155. };
  22156. Camera.prototype._updateCache = function (ignoreParentClass) {
  22157. if (!ignoreParentClass) {
  22158. _super.prototype._updateCache.call(this);
  22159. }
  22160. this._cache.position.copyFrom(this.position);
  22161. this._cache.upVector.copyFrom(this.upVector);
  22162. };
  22163. // Synchronized
  22164. Camera.prototype._isSynchronized = function () {
  22165. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22166. };
  22167. Camera.prototype._isSynchronizedViewMatrix = function () {
  22168. if (!_super.prototype._isSynchronized.call(this))
  22169. return false;
  22170. return this._cache.position.equals(this.position)
  22171. && this._cache.upVector.equals(this.upVector)
  22172. && this.isSynchronizedWithParent();
  22173. };
  22174. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22175. var check = this._cache.mode === this.mode
  22176. && this._cache.minZ === this.minZ
  22177. && this._cache.maxZ === this.maxZ;
  22178. if (!check) {
  22179. return false;
  22180. }
  22181. var engine = this.getEngine();
  22182. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22183. check = this._cache.fov === this.fov
  22184. && this._cache.fovMode === this.fovMode
  22185. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22186. }
  22187. else {
  22188. check = this._cache.orthoLeft === this.orthoLeft
  22189. && this._cache.orthoRight === this.orthoRight
  22190. && this._cache.orthoBottom === this.orthoBottom
  22191. && this._cache.orthoTop === this.orthoTop
  22192. && this._cache.renderWidth === engine.getRenderWidth()
  22193. && this._cache.renderHeight === engine.getRenderHeight();
  22194. }
  22195. return check;
  22196. };
  22197. // Controls
  22198. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22199. };
  22200. Camera.prototype.detachControl = function (element) {
  22201. };
  22202. Camera.prototype.update = function () {
  22203. this._checkInputs();
  22204. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22205. this._updateRigCameras();
  22206. }
  22207. };
  22208. Camera.prototype._checkInputs = function () {
  22209. this.onAfterCheckInputsObservable.notifyObservers(this);
  22210. };
  22211. Object.defineProperty(Camera.prototype, "rigCameras", {
  22212. get: function () {
  22213. return this._rigCameras;
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22219. get: function () {
  22220. return this._rigPostProcess;
  22221. },
  22222. enumerable: true,
  22223. configurable: true
  22224. });
  22225. /**
  22226. * Internal, gets the first post proces.
  22227. * @returns the first post process to be run on this camera.
  22228. */
  22229. Camera.prototype._getFirstPostProcess = function () {
  22230. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22231. if (this._postProcesses[ppIndex] !== null) {
  22232. return this._postProcesses[ppIndex];
  22233. }
  22234. }
  22235. return null;
  22236. };
  22237. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22238. // invalidate framebuffer
  22239. var firstPostProcess = this._getFirstPostProcess();
  22240. if (firstPostProcess) {
  22241. firstPostProcess.markTextureDirty();
  22242. }
  22243. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22244. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22245. var cam = this._rigCameras[i];
  22246. var rigPostProcess = cam._rigPostProcess;
  22247. // for VR rig, there does not have to be a post process
  22248. if (rigPostProcess) {
  22249. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22250. if (isPass) {
  22251. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22252. cam.isIntermediate = this._postProcesses.length === 0;
  22253. }
  22254. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22255. rigPostProcess.markTextureDirty();
  22256. }
  22257. else {
  22258. cam._postProcesses = this._postProcesses.slice(0);
  22259. }
  22260. }
  22261. };
  22262. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22263. if (insertAt === void 0) { insertAt = null; }
  22264. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22265. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22266. return 0;
  22267. }
  22268. if (insertAt == null || insertAt < 0) {
  22269. this._postProcesses.push(postProcess);
  22270. }
  22271. else if (this._postProcesses[insertAt] === null) {
  22272. this._postProcesses[insertAt] = postProcess;
  22273. }
  22274. else {
  22275. this._postProcesses.splice(insertAt, 0, postProcess);
  22276. }
  22277. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22278. return this._postProcesses.indexOf(postProcess);
  22279. };
  22280. Camera.prototype.detachPostProcess = function (postProcess) {
  22281. var idx = this._postProcesses.indexOf(postProcess);
  22282. if (idx !== -1) {
  22283. this._postProcesses[idx] = null;
  22284. }
  22285. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22286. };
  22287. Camera.prototype.getWorldMatrix = function () {
  22288. if (this._isSynchronizedViewMatrix()) {
  22289. return this._worldMatrix;
  22290. }
  22291. // Getting the the view matrix will also compute the world matrix.
  22292. this.getViewMatrix();
  22293. return this._worldMatrix;
  22294. };
  22295. Camera.prototype._getViewMatrix = function () {
  22296. return BABYLON.Matrix.Identity();
  22297. };
  22298. Camera.prototype.getViewMatrix = function (force) {
  22299. if (!force && this._isSynchronizedViewMatrix()) {
  22300. return this._computedViewMatrix;
  22301. }
  22302. this.updateCache();
  22303. this._computedViewMatrix = this._getViewMatrix();
  22304. this._currentRenderId = this.getScene().getRenderId();
  22305. this._childRenderId = this._currentRenderId;
  22306. this._refreshFrustumPlanes = true;
  22307. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22308. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22309. }
  22310. this.onViewMatrixChangedObservable.notifyObservers(this);
  22311. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22312. return this._computedViewMatrix;
  22313. };
  22314. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22315. this._doNotComputeProjectionMatrix = true;
  22316. if (projection !== undefined) {
  22317. this._projectionMatrix = projection;
  22318. }
  22319. };
  22320. ;
  22321. Camera.prototype.unfreezeProjectionMatrix = function () {
  22322. this._doNotComputeProjectionMatrix = false;
  22323. };
  22324. ;
  22325. Camera.prototype.getProjectionMatrix = function (force) {
  22326. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22327. return this._projectionMatrix;
  22328. }
  22329. // Cache
  22330. this._cache.mode = this.mode;
  22331. this._cache.minZ = this.minZ;
  22332. this._cache.maxZ = this.maxZ;
  22333. // Matrix
  22334. this._refreshFrustumPlanes = true;
  22335. var engine = this.getEngine();
  22336. var scene = this.getScene();
  22337. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22338. this._cache.fov = this.fov;
  22339. this._cache.fovMode = this.fovMode;
  22340. this._cache.aspectRatio = engine.getAspectRatio(this);
  22341. if (this.minZ <= 0) {
  22342. this.minZ = 0.1;
  22343. }
  22344. if (scene.useRightHandedSystem) {
  22345. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22346. }
  22347. else {
  22348. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22349. }
  22350. }
  22351. else {
  22352. var halfWidth = engine.getRenderWidth() / 2.0;
  22353. var halfHeight = engine.getRenderHeight() / 2.0;
  22354. if (scene.useRightHandedSystem) {
  22355. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22356. }
  22357. else {
  22358. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22359. }
  22360. this._cache.orthoLeft = this.orthoLeft;
  22361. this._cache.orthoRight = this.orthoRight;
  22362. this._cache.orthoBottom = this.orthoBottom;
  22363. this._cache.orthoTop = this.orthoTop;
  22364. this._cache.renderWidth = engine.getRenderWidth();
  22365. this._cache.renderHeight = engine.getRenderHeight();
  22366. }
  22367. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22368. return this._projectionMatrix;
  22369. };
  22370. /**
  22371. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22372. * @returns a Matrix
  22373. */
  22374. Camera.prototype.getTransformationMatrix = function () {
  22375. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22376. return this._transformMatrix;
  22377. };
  22378. Camera.prototype.updateFrustumPlanes = function () {
  22379. if (!this._refreshFrustumPlanes) {
  22380. return;
  22381. }
  22382. this.getTransformationMatrix();
  22383. if (!this._frustumPlanes) {
  22384. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22385. }
  22386. else {
  22387. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22388. }
  22389. this._refreshFrustumPlanes = false;
  22390. };
  22391. Camera.prototype.isInFrustum = function (target) {
  22392. this.updateFrustumPlanes();
  22393. return target.isInFrustum(this._frustumPlanes);
  22394. };
  22395. Camera.prototype.isCompletelyInFrustum = function (target) {
  22396. this.updateFrustumPlanes();
  22397. return target.isCompletelyInFrustum(this._frustumPlanes);
  22398. };
  22399. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22400. if (length === void 0) { length = 100; }
  22401. if (!transform) {
  22402. transform = this.getWorldMatrix();
  22403. }
  22404. if (!origin) {
  22405. origin = this.position;
  22406. }
  22407. var forward = new BABYLON.Vector3(0, 0, 1);
  22408. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22409. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22410. return new BABYLON.Ray(origin, direction, length);
  22411. };
  22412. /**
  22413. * Releases resources associated with this node.
  22414. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22415. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22416. */
  22417. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22418. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22419. // Observables
  22420. this.onViewMatrixChangedObservable.clear();
  22421. this.onProjectionMatrixChangedObservable.clear();
  22422. this.onAfterCheckInputsObservable.clear();
  22423. this.onRestoreStateObservable.clear();
  22424. // Inputs
  22425. if (this.inputs) {
  22426. this.inputs.clear();
  22427. }
  22428. // Animations
  22429. this.getScene().stopAnimation(this);
  22430. // Remove from scene
  22431. this.getScene().removeCamera(this);
  22432. while (this._rigCameras.length > 0) {
  22433. var camera = this._rigCameras.pop();
  22434. if (camera) {
  22435. camera.dispose();
  22436. }
  22437. }
  22438. // Postprocesses
  22439. if (this._rigPostProcess) {
  22440. this._rigPostProcess.dispose(this);
  22441. this._rigPostProcess = null;
  22442. this._postProcesses = [];
  22443. }
  22444. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22445. this._rigPostProcess = null;
  22446. this._postProcesses = [];
  22447. }
  22448. else {
  22449. var i = this._postProcesses.length;
  22450. while (--i >= 0) {
  22451. var postProcess = this._postProcesses[i];
  22452. if (postProcess) {
  22453. postProcess.dispose(this);
  22454. }
  22455. }
  22456. }
  22457. // Render targets
  22458. var i = this.customRenderTargets.length;
  22459. while (--i >= 0) {
  22460. this.customRenderTargets[i].dispose();
  22461. }
  22462. this.customRenderTargets = [];
  22463. // Active Meshes
  22464. this._activeMeshes.dispose();
  22465. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22466. };
  22467. Object.defineProperty(Camera.prototype, "leftCamera", {
  22468. // ---- Camera rigs section ----
  22469. get: function () {
  22470. if (this._rigCameras.length < 1) {
  22471. return null;
  22472. }
  22473. return this._rigCameras[0];
  22474. },
  22475. enumerable: true,
  22476. configurable: true
  22477. });
  22478. Object.defineProperty(Camera.prototype, "rightCamera", {
  22479. get: function () {
  22480. if (this._rigCameras.length < 2) {
  22481. return null;
  22482. }
  22483. return this._rigCameras[1];
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Camera.prototype.getLeftTarget = function () {
  22489. if (this._rigCameras.length < 1) {
  22490. return null;
  22491. }
  22492. return this._rigCameras[0].getTarget();
  22493. };
  22494. Camera.prototype.getRightTarget = function () {
  22495. if (this._rigCameras.length < 2) {
  22496. return null;
  22497. }
  22498. return this._rigCameras[1].getTarget();
  22499. };
  22500. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22501. if (this.cameraRigMode === mode) {
  22502. return;
  22503. }
  22504. while (this._rigCameras.length > 0) {
  22505. var camera = this._rigCameras.pop();
  22506. if (camera) {
  22507. camera.dispose();
  22508. }
  22509. }
  22510. this.cameraRigMode = mode;
  22511. this._cameraRigParams = {};
  22512. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22513. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22514. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22515. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22516. // create the rig cameras, unless none
  22517. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22518. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22519. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22520. if (leftCamera && rightCamera) {
  22521. this._rigCameras.push(leftCamera);
  22522. this._rigCameras.push(rightCamera);
  22523. }
  22524. }
  22525. switch (this.cameraRigMode) {
  22526. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22527. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22528. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22529. break;
  22530. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22531. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22532. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22533. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22534. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22535. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22536. break;
  22537. case Camera.RIG_MODE_VR:
  22538. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22539. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22540. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22541. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22542. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22543. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22544. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22545. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22546. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22547. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22548. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22549. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22550. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22551. if (metrics.compensateDistortion) {
  22552. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22553. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22554. }
  22555. break;
  22556. case Camera.RIG_MODE_WEBVR:
  22557. if (rigParams.vrDisplay) {
  22558. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22559. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22560. //Left eye
  22561. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22562. this._rigCameras[0].setCameraRigParameter("left", true);
  22563. //leaving this for future reference
  22564. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22565. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22566. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22567. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22568. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22569. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22570. this._rigCameras[0].parent = this;
  22571. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22572. //Right eye
  22573. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22574. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22575. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22576. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22577. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22578. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22579. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22580. this._rigCameras[1].parent = this;
  22581. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22582. if (Camera.UseAlternateWebVRRendering) {
  22583. this._rigCameras[1]._skipRendering = true;
  22584. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22585. }
  22586. }
  22587. break;
  22588. }
  22589. this._cascadePostProcessesToRigCams();
  22590. this.update();
  22591. };
  22592. Camera.prototype._getVRProjectionMatrix = function () {
  22593. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22594. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22595. return this._projectionMatrix;
  22596. };
  22597. Camera.prototype._updateCameraRotationMatrix = function () {
  22598. //Here for WebVR
  22599. };
  22600. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22601. //Here for WebVR
  22602. };
  22603. /**
  22604. * This function MUST be overwritten by the different WebVR cameras available.
  22605. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22606. */
  22607. Camera.prototype._getWebVRProjectionMatrix = function () {
  22608. return BABYLON.Matrix.Identity();
  22609. };
  22610. /**
  22611. * This function MUST be overwritten by the different WebVR cameras available.
  22612. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22613. */
  22614. Camera.prototype._getWebVRViewMatrix = function () {
  22615. return BABYLON.Matrix.Identity();
  22616. };
  22617. Camera.prototype.setCameraRigParameter = function (name, value) {
  22618. if (!this._cameraRigParams) {
  22619. this._cameraRigParams = {};
  22620. }
  22621. this._cameraRigParams[name] = value;
  22622. //provisionnally:
  22623. if (name === "interaxialDistance") {
  22624. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22625. }
  22626. };
  22627. /**
  22628. * needs to be overridden by children so sub has required properties to be copied
  22629. */
  22630. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22631. return null;
  22632. };
  22633. /**
  22634. * May need to be overridden by children
  22635. */
  22636. Camera.prototype._updateRigCameras = function () {
  22637. for (var i = 0; i < this._rigCameras.length; i++) {
  22638. this._rigCameras[i].minZ = this.minZ;
  22639. this._rigCameras[i].maxZ = this.maxZ;
  22640. this._rigCameras[i].fov = this.fov;
  22641. }
  22642. // only update viewport when ANAGLYPH
  22643. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22644. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22645. }
  22646. };
  22647. Camera.prototype._setupInputs = function () {
  22648. };
  22649. Camera.prototype.serialize = function () {
  22650. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22651. // Type
  22652. serializationObject.type = this.getClassName();
  22653. // Parent
  22654. if (this.parent) {
  22655. serializationObject.parentId = this.parent.id;
  22656. }
  22657. if (this.inputs) {
  22658. this.inputs.serialize(serializationObject);
  22659. }
  22660. // Animations
  22661. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22662. serializationObject.ranges = this.serializeAnimationRanges();
  22663. return serializationObject;
  22664. };
  22665. Camera.prototype.clone = function (name) {
  22666. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22667. };
  22668. Camera.prototype.getDirection = function (localAxis) {
  22669. var result = BABYLON.Vector3.Zero();
  22670. this.getDirectionToRef(localAxis, result);
  22671. return result;
  22672. };
  22673. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22674. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22675. };
  22676. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22677. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22678. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22679. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22680. interaxial_distance: interaxial_distance,
  22681. isStereoscopicSideBySide: isStereoscopicSideBySide
  22682. });
  22683. if (constructorFunc) {
  22684. return constructorFunc;
  22685. }
  22686. // Default to universal camera
  22687. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22688. };
  22689. Camera.prototype.computeWorldMatrix = function () {
  22690. return this.getWorldMatrix();
  22691. };
  22692. Camera.Parse = function (parsedCamera, scene) {
  22693. var type = parsedCamera.type;
  22694. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22695. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22696. // Parent
  22697. if (parsedCamera.parentId) {
  22698. camera._waitingParentId = parsedCamera.parentId;
  22699. }
  22700. //If camera has an input manager, let it parse inputs settings
  22701. if (camera.inputs) {
  22702. camera.inputs.parse(parsedCamera);
  22703. camera._setupInputs();
  22704. }
  22705. if (camera.setPosition) { // need to force position
  22706. camera.position.copyFromFloats(0, 0, 0);
  22707. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22708. }
  22709. // Target
  22710. if (parsedCamera.target) {
  22711. if (camera.setTarget) {
  22712. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22713. }
  22714. }
  22715. // Apply 3d rig, when found
  22716. if (parsedCamera.cameraRigMode) {
  22717. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22718. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22719. }
  22720. // Animations
  22721. if (parsedCamera.animations) {
  22722. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22723. var parsedAnimation = parsedCamera.animations[animationIndex];
  22724. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22725. }
  22726. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22727. }
  22728. if (parsedCamera.autoAnimate) {
  22729. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22730. }
  22731. return camera;
  22732. };
  22733. // Statics
  22734. Camera._PERSPECTIVE_CAMERA = 0;
  22735. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22736. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22737. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22738. Camera._RIG_MODE_NONE = 0;
  22739. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22740. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22741. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22742. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22743. Camera._RIG_MODE_VR = 20;
  22744. Camera._RIG_MODE_WEBVR = 21;
  22745. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22746. Camera.UseAlternateWebVRRendering = false;
  22747. __decorate([
  22748. BABYLON.serializeAsVector3()
  22749. ], Camera.prototype, "position", void 0);
  22750. __decorate([
  22751. BABYLON.serializeAsVector3()
  22752. ], Camera.prototype, "upVector", void 0);
  22753. __decorate([
  22754. BABYLON.serialize()
  22755. ], Camera.prototype, "orthoLeft", void 0);
  22756. __decorate([
  22757. BABYLON.serialize()
  22758. ], Camera.prototype, "orthoRight", void 0);
  22759. __decorate([
  22760. BABYLON.serialize()
  22761. ], Camera.prototype, "orthoBottom", void 0);
  22762. __decorate([
  22763. BABYLON.serialize()
  22764. ], Camera.prototype, "orthoTop", void 0);
  22765. __decorate([
  22766. BABYLON.serialize()
  22767. ], Camera.prototype, "fov", void 0);
  22768. __decorate([
  22769. BABYLON.serialize()
  22770. ], Camera.prototype, "minZ", void 0);
  22771. __decorate([
  22772. BABYLON.serialize()
  22773. ], Camera.prototype, "maxZ", void 0);
  22774. __decorate([
  22775. BABYLON.serialize()
  22776. ], Camera.prototype, "inertia", void 0);
  22777. __decorate([
  22778. BABYLON.serialize()
  22779. ], Camera.prototype, "mode", void 0);
  22780. __decorate([
  22781. BABYLON.serialize()
  22782. ], Camera.prototype, "layerMask", void 0);
  22783. __decorate([
  22784. BABYLON.serialize()
  22785. ], Camera.prototype, "fovMode", void 0);
  22786. __decorate([
  22787. BABYLON.serialize()
  22788. ], Camera.prototype, "cameraRigMode", void 0);
  22789. __decorate([
  22790. BABYLON.serialize()
  22791. ], Camera.prototype, "interaxialDistance", void 0);
  22792. __decorate([
  22793. BABYLON.serialize()
  22794. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22795. return Camera;
  22796. }(BABYLON.Node));
  22797. BABYLON.Camera = Camera;
  22798. })(BABYLON || (BABYLON = {}));
  22799. //# sourceMappingURL=babylon.camera.js.map
  22800. var BABYLON;
  22801. (function (BABYLON) {
  22802. var RenderingManager = /** @class */ (function () {
  22803. function RenderingManager(scene) {
  22804. /**
  22805. * Hidden
  22806. */
  22807. this._useSceneAutoClearSetup = false;
  22808. this._renderingGroups = new Array();
  22809. this._autoClearDepthStencil = {};
  22810. this._customOpaqueSortCompareFn = {};
  22811. this._customAlphaTestSortCompareFn = {};
  22812. this._customTransparentSortCompareFn = {};
  22813. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22814. this._scene = scene;
  22815. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22816. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22817. }
  22818. }
  22819. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22820. if (depth === void 0) { depth = true; }
  22821. if (stencil === void 0) { stencil = true; }
  22822. if (this._depthStencilBufferAlreadyCleaned) {
  22823. return;
  22824. }
  22825. this._scene.getEngine().clear(null, false, depth, stencil);
  22826. this._depthStencilBufferAlreadyCleaned = true;
  22827. };
  22828. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22829. // Update the observable context (not null as it only goes away on dispose)
  22830. var info = this._renderingGroupInfo;
  22831. info.scene = this._scene;
  22832. info.camera = this._scene.activeCamera;
  22833. // Dispatch sprites
  22834. if (renderSprites) {
  22835. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22836. var manager = this._scene.spriteManagers[index];
  22837. this.dispatchSprites(manager);
  22838. }
  22839. }
  22840. // Render
  22841. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22842. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22843. var renderingGroup = this._renderingGroups[index];
  22844. if (!renderingGroup)
  22845. continue;
  22846. var renderingGroupMask = Math.pow(2, index);
  22847. info.renderingGroupId = index;
  22848. // Before Observable
  22849. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22850. // Clear depth/stencil if needed
  22851. if (RenderingManager.AUTOCLEAR) {
  22852. var autoClear = this._useSceneAutoClearSetup ?
  22853. this._scene.getAutoClearDepthStencilSetup(index) :
  22854. this._autoClearDepthStencil[index];
  22855. if (autoClear && autoClear.autoClear) {
  22856. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22857. }
  22858. }
  22859. // Render
  22860. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22861. var step = _a[_i];
  22862. step.action(index);
  22863. }
  22864. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22865. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22866. var step = _c[_b];
  22867. step.action(index);
  22868. }
  22869. // After Observable
  22870. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22871. }
  22872. };
  22873. RenderingManager.prototype.reset = function () {
  22874. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22875. var renderingGroup = this._renderingGroups[index];
  22876. if (renderingGroup) {
  22877. renderingGroup.prepare();
  22878. }
  22879. }
  22880. };
  22881. RenderingManager.prototype.dispose = function () {
  22882. this.freeRenderingGroups();
  22883. this._renderingGroups.length = 0;
  22884. this._renderingGroupInfo = null;
  22885. };
  22886. /**
  22887. * Clear the info related to rendering groups preventing retention points during dispose.
  22888. */
  22889. RenderingManager.prototype.freeRenderingGroups = function () {
  22890. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22891. var renderingGroup = this._renderingGroups[index];
  22892. if (renderingGroup) {
  22893. renderingGroup.dispose();
  22894. }
  22895. }
  22896. };
  22897. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22898. if (this._renderingGroups[renderingGroupId] === undefined) {
  22899. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22900. }
  22901. };
  22902. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22903. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22904. this._prepareRenderingGroup(renderingGroupId);
  22905. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22906. };
  22907. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22908. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22909. this._prepareRenderingGroup(renderingGroupId);
  22910. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22911. };
  22912. /**
  22913. * @param subMesh The submesh to dispatch
  22914. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22915. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22916. */
  22917. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22918. if (mesh === undefined) {
  22919. mesh = subMesh.getMesh();
  22920. }
  22921. var renderingGroupId = mesh.renderingGroupId || 0;
  22922. this._prepareRenderingGroup(renderingGroupId);
  22923. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22924. };
  22925. /**
  22926. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22927. * This allowed control for front to back rendering or reversly depending of the special needs.
  22928. *
  22929. * @param renderingGroupId The rendering group id corresponding to its index
  22930. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22931. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22932. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22933. */
  22934. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22935. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22936. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22937. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22938. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22939. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22940. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22941. if (this._renderingGroups[renderingGroupId]) {
  22942. var group = this._renderingGroups[renderingGroupId];
  22943. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22944. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22945. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22946. }
  22947. };
  22948. /**
  22949. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22950. *
  22951. * @param renderingGroupId The rendering group id corresponding to its index
  22952. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22953. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22954. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22955. */
  22956. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22957. if (depth === void 0) { depth = true; }
  22958. if (stencil === void 0) { stencil = true; }
  22959. this._autoClearDepthStencil[renderingGroupId] = {
  22960. autoClear: autoClearDepthStencil,
  22961. depth: depth,
  22962. stencil: stencil
  22963. };
  22964. };
  22965. /**
  22966. * Gets the current auto clear configuration for one rendering group of the rendering
  22967. * manager.
  22968. * @param index the rendering group index to get the information for
  22969. * @returns The auto clear setup for the requested rendering group
  22970. */
  22971. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  22972. return this._autoClearDepthStencil[index];
  22973. };
  22974. /**
  22975. * The max id used for rendering groups (not included)
  22976. */
  22977. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22978. /**
  22979. * The min id used for rendering groups (included)
  22980. */
  22981. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22982. /**
  22983. * Used to globally prevent autoclearing scenes.
  22984. */
  22985. RenderingManager.AUTOCLEAR = true;
  22986. return RenderingManager;
  22987. }());
  22988. BABYLON.RenderingManager = RenderingManager;
  22989. })(BABYLON || (BABYLON = {}));
  22990. //# sourceMappingURL=babylon.renderingManager.js.map
  22991. var BABYLON;
  22992. (function (BABYLON) {
  22993. var RenderingGroup = /** @class */ (function () {
  22994. /**
  22995. * Creates a new rendering group.
  22996. * @param index The rendering group index
  22997. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22998. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22999. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23000. */
  23001. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23002. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23003. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23004. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23005. this.index = index;
  23006. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23007. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23008. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23009. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23010. this._particleSystems = new BABYLON.SmartArray(256);
  23011. this._spriteManagers = new BABYLON.SmartArray(256);
  23012. this._edgesRenderers = new BABYLON.SmartArray(16);
  23013. this._scene = scene;
  23014. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23015. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23016. this.transparentSortCompareFn = transparentSortCompareFn;
  23017. }
  23018. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23019. /**
  23020. * Set the opaque sort comparison function.
  23021. * If null the sub meshes will be render in the order they were created
  23022. */
  23023. set: function (value) {
  23024. this._opaqueSortCompareFn = value;
  23025. if (value) {
  23026. this._renderOpaque = this.renderOpaqueSorted;
  23027. }
  23028. else {
  23029. this._renderOpaque = RenderingGroup.renderUnsorted;
  23030. }
  23031. },
  23032. enumerable: true,
  23033. configurable: true
  23034. });
  23035. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23036. /**
  23037. * Set the alpha test sort comparison function.
  23038. * If null the sub meshes will be render in the order they were created
  23039. */
  23040. set: function (value) {
  23041. this._alphaTestSortCompareFn = value;
  23042. if (value) {
  23043. this._renderAlphaTest = this.renderAlphaTestSorted;
  23044. }
  23045. else {
  23046. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23047. }
  23048. },
  23049. enumerable: true,
  23050. configurable: true
  23051. });
  23052. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23053. /**
  23054. * Set the transparent sort comparison function.
  23055. * If null the sub meshes will be render in the order they were created
  23056. */
  23057. set: function (value) {
  23058. if (value) {
  23059. this._transparentSortCompareFn = value;
  23060. }
  23061. else {
  23062. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23063. }
  23064. this._renderTransparent = this.renderTransparentSorted;
  23065. },
  23066. enumerable: true,
  23067. configurable: true
  23068. });
  23069. /**
  23070. * Render all the sub meshes contained in the group.
  23071. * @param customRenderFunction Used to override the default render behaviour of the group.
  23072. * @returns true if rendered some submeshes.
  23073. */
  23074. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23075. if (customRenderFunction) {
  23076. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23077. return;
  23078. }
  23079. var engine = this._scene.getEngine();
  23080. // Depth only
  23081. if (this._depthOnlySubMeshes.length !== 0) {
  23082. engine.setColorWrite(false);
  23083. this._renderAlphaTest(this._depthOnlySubMeshes);
  23084. engine.setColorWrite(true);
  23085. }
  23086. // Opaque
  23087. if (this._opaqueSubMeshes.length !== 0) {
  23088. this._renderOpaque(this._opaqueSubMeshes);
  23089. }
  23090. // Alpha test
  23091. if (this._alphaTestSubMeshes.length !== 0) {
  23092. this._renderAlphaTest(this._alphaTestSubMeshes);
  23093. }
  23094. var stencilState = engine.getStencilBuffer();
  23095. engine.setStencilBuffer(false);
  23096. // Sprites
  23097. if (renderSprites) {
  23098. this._renderSprites();
  23099. }
  23100. // Particles
  23101. if (renderParticles) {
  23102. this._renderParticles(activeMeshes);
  23103. }
  23104. if (this.onBeforeTransparentRendering) {
  23105. this.onBeforeTransparentRendering();
  23106. }
  23107. // Transparent
  23108. if (this._transparentSubMeshes.length !== 0) {
  23109. this._renderTransparent(this._transparentSubMeshes);
  23110. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23111. }
  23112. // Set back stencil to false in case it changes before the edge renderer.
  23113. engine.setStencilBuffer(false);
  23114. // Edges
  23115. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23116. this._edgesRenderers.data[edgesRendererIndex].render();
  23117. }
  23118. // Restore Stencil state.
  23119. engine.setStencilBuffer(stencilState);
  23120. };
  23121. /**
  23122. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23123. * @param subMeshes The submeshes to render
  23124. */
  23125. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23126. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23127. };
  23128. /**
  23129. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23130. * @param subMeshes The submeshes to render
  23131. */
  23132. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23133. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23134. };
  23135. /**
  23136. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23137. * @param subMeshes The submeshes to render
  23138. */
  23139. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23140. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23141. };
  23142. /**
  23143. * Renders the submeshes in a specified order.
  23144. * @param subMeshes The submeshes to sort before render
  23145. * @param sortCompareFn The comparison function use to sort
  23146. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23147. * @param transparent Specifies to activate blending if true
  23148. */
  23149. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23150. var subIndex = 0;
  23151. var subMesh;
  23152. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23153. for (; subIndex < subMeshes.length; subIndex++) {
  23154. subMesh = subMeshes.data[subIndex];
  23155. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23156. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23157. }
  23158. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23159. if (sortCompareFn) {
  23160. sortedArray.sort(sortCompareFn);
  23161. }
  23162. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23163. subMesh = sortedArray[subIndex];
  23164. if (transparent) {
  23165. var material = subMesh.getMaterial();
  23166. if (material && material.needDepthPrePass) {
  23167. var engine = material.getScene().getEngine();
  23168. engine.setColorWrite(false);
  23169. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23170. subMesh.render(false);
  23171. engine.setColorWrite(true);
  23172. }
  23173. }
  23174. subMesh.render(transparent);
  23175. }
  23176. };
  23177. /**
  23178. * Renders the submeshes in the order they were dispatched (no sort applied).
  23179. * @param subMeshes The submeshes to render
  23180. */
  23181. RenderingGroup.renderUnsorted = function (subMeshes) {
  23182. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23183. var submesh = subMeshes.data[subIndex];
  23184. submesh.render(false);
  23185. }
  23186. };
  23187. /**
  23188. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23189. * are rendered back to front if in the same alpha index.
  23190. *
  23191. * @param a The first submesh
  23192. * @param b The second submesh
  23193. * @returns The result of the comparison
  23194. */
  23195. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23196. // Alpha index first
  23197. if (a._alphaIndex > b._alphaIndex) {
  23198. return 1;
  23199. }
  23200. if (a._alphaIndex < b._alphaIndex) {
  23201. return -1;
  23202. }
  23203. // Then distance to camera
  23204. return RenderingGroup.backToFrontSortCompare(a, b);
  23205. };
  23206. /**
  23207. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23208. * are rendered back to front.
  23209. *
  23210. * @param a The first submesh
  23211. * @param b The second submesh
  23212. * @returns The result of the comparison
  23213. */
  23214. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23215. // Then distance to camera
  23216. if (a._distanceToCamera < b._distanceToCamera) {
  23217. return 1;
  23218. }
  23219. if (a._distanceToCamera > b._distanceToCamera) {
  23220. return -1;
  23221. }
  23222. return 0;
  23223. };
  23224. /**
  23225. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23226. * are rendered front to back (prevent overdraw).
  23227. *
  23228. * @param a The first submesh
  23229. * @param b The second submesh
  23230. * @returns The result of the comparison
  23231. */
  23232. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23233. // Then distance to camera
  23234. if (a._distanceToCamera < b._distanceToCamera) {
  23235. return -1;
  23236. }
  23237. if (a._distanceToCamera > b._distanceToCamera) {
  23238. return 1;
  23239. }
  23240. return 0;
  23241. };
  23242. /**
  23243. * Resets the different lists of submeshes to prepare a new frame.
  23244. */
  23245. RenderingGroup.prototype.prepare = function () {
  23246. this._opaqueSubMeshes.reset();
  23247. this._transparentSubMeshes.reset();
  23248. this._alphaTestSubMeshes.reset();
  23249. this._depthOnlySubMeshes.reset();
  23250. this._particleSystems.reset();
  23251. this._spriteManagers.reset();
  23252. this._edgesRenderers.reset();
  23253. };
  23254. RenderingGroup.prototype.dispose = function () {
  23255. this._opaqueSubMeshes.dispose();
  23256. this._transparentSubMeshes.dispose();
  23257. this._alphaTestSubMeshes.dispose();
  23258. this._depthOnlySubMeshes.dispose();
  23259. this._particleSystems.dispose();
  23260. this._spriteManagers.dispose();
  23261. this._edgesRenderers.dispose();
  23262. };
  23263. /**
  23264. * Inserts the submesh in its correct queue depending on its material.
  23265. * @param subMesh The submesh to dispatch
  23266. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23267. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23268. */
  23269. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23270. // Get mesh and materials if not provided
  23271. if (mesh === undefined) {
  23272. mesh = subMesh.getMesh();
  23273. }
  23274. if (material === undefined) {
  23275. material = subMesh.getMaterial();
  23276. }
  23277. if (material === null || material === undefined) {
  23278. return;
  23279. }
  23280. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23281. this._transparentSubMeshes.push(subMesh);
  23282. }
  23283. else if (material.needAlphaTesting()) { // Alpha test
  23284. if (material.needDepthPrePass) {
  23285. this._depthOnlySubMeshes.push(subMesh);
  23286. }
  23287. this._alphaTestSubMeshes.push(subMesh);
  23288. }
  23289. else {
  23290. if (material.needDepthPrePass) {
  23291. this._depthOnlySubMeshes.push(subMesh);
  23292. }
  23293. this._opaqueSubMeshes.push(subMesh); // Opaque
  23294. }
  23295. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23296. this._edgesRenderers.push(mesh._edgesRenderer);
  23297. }
  23298. };
  23299. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23300. this._spriteManagers.push(spriteManager);
  23301. };
  23302. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23303. this._particleSystems.push(particleSystem);
  23304. };
  23305. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23306. if (this._particleSystems.length === 0) {
  23307. return;
  23308. }
  23309. // Particles
  23310. var activeCamera = this._scene.activeCamera;
  23311. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23312. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23313. var particleSystem = this._particleSystems.data[particleIndex];
  23314. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23315. continue;
  23316. }
  23317. var emitter = particleSystem.emitter;
  23318. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23319. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23320. }
  23321. }
  23322. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23323. };
  23324. RenderingGroup.prototype._renderSprites = function () {
  23325. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23326. return;
  23327. }
  23328. // Sprites
  23329. var activeCamera = this._scene.activeCamera;
  23330. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23331. for (var id = 0; id < this._spriteManagers.length; id++) {
  23332. var spriteManager = this._spriteManagers.data[id];
  23333. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23334. spriteManager.render();
  23335. }
  23336. }
  23337. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23338. };
  23339. return RenderingGroup;
  23340. }());
  23341. BABYLON.RenderingGroup = RenderingGroup;
  23342. })(BABYLON || (BABYLON = {}));
  23343. //# sourceMappingURL=babylon.renderingGroup.js.map
  23344. var BABYLON;
  23345. (function (BABYLON) {
  23346. /**
  23347. * Groups all the scene component constants in one place to ease maintenance.
  23348. * @hidden
  23349. */
  23350. var SceneComponentConstants = /** @class */ (function () {
  23351. function SceneComponentConstants() {
  23352. }
  23353. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23354. SceneComponentConstants.NAME_LAYER = "Layer";
  23355. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23356. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23357. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23358. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23359. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23360. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23361. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23362. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23363. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23364. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23365. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23366. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23367. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23368. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23369. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23370. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23371. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23372. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23373. return SceneComponentConstants;
  23374. }());
  23375. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23376. /**
  23377. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23378. * @hidden
  23379. */
  23380. var Stage = /** @class */ (function (_super) {
  23381. __extends(Stage, _super);
  23382. /**
  23383. * Hide ctor from the rest of the world.
  23384. * @param items The items to add.
  23385. */
  23386. function Stage(items) {
  23387. return _super.apply(this, items) || this;
  23388. }
  23389. /**
  23390. * Creates a new Stage.
  23391. * @returns A new instance of a Stage
  23392. */
  23393. Stage.Create = function () {
  23394. return Object.create(Stage.prototype);
  23395. };
  23396. /**
  23397. * Registers a step in an ordered way in the targeted stage.
  23398. * @param index Defines the position to register the step in
  23399. * @param component Defines the component attached to the step
  23400. * @param action Defines the action to launch during the step
  23401. */
  23402. Stage.prototype.registerStep = function (index, component, action) {
  23403. var i = 0;
  23404. var maxIndex = Number.MAX_VALUE;
  23405. for (; i < this.length && i < maxIndex; i++) {
  23406. var step = this[i];
  23407. maxIndex = step.index;
  23408. }
  23409. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23410. };
  23411. /**
  23412. * Clears all the steps from the stage.
  23413. */
  23414. Stage.prototype.clear = function () {
  23415. this.length = 0;
  23416. };
  23417. return Stage;
  23418. }(Array));
  23419. BABYLON.Stage = Stage;
  23420. })(BABYLON || (BABYLON = {}));
  23421. //# sourceMappingURL=babylon.sceneComponent.js.map
  23422. var BABYLON;
  23423. (function (BABYLON) {
  23424. /**
  23425. * Base class of the scene acting as a container for the different elements composing a scene.
  23426. * This class is dynamically extended by the different components of the scene increasing
  23427. * flexibility and reducing coupling
  23428. */
  23429. var AbstractScene = /** @class */ (function () {
  23430. function AbstractScene() {
  23431. /** All of the cameras added to this scene
  23432. * @see http://doc.babylonjs.com/babylon101/cameras
  23433. */
  23434. this.cameras = new Array();
  23435. /**
  23436. * All of the lights added to this scene
  23437. * @see http://doc.babylonjs.com/babylon101/lights
  23438. */
  23439. this.lights = new Array();
  23440. /**
  23441. * All of the (abstract) meshes added to this scene
  23442. */
  23443. this.meshes = new Array();
  23444. /**
  23445. * The list of skeletons added to the scene
  23446. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23447. */
  23448. this.skeletons = new Array();
  23449. /**
  23450. * All of the particle systems added to this scene
  23451. * @see http://doc.babylonjs.com/babylon101/particles
  23452. */
  23453. this.particleSystems = new Array();
  23454. /**
  23455. * Gets a list of Animations associated with the scene
  23456. */
  23457. this.animations = [];
  23458. /**
  23459. * All of the animation groups added to this scene
  23460. * @see http://doc.babylonjs.com/how_to/group
  23461. */
  23462. this.animationGroups = new Array();
  23463. /**
  23464. * All of the multi-materials added to this scene
  23465. * @see http://doc.babylonjs.com/how_to/multi_materials
  23466. */
  23467. this.multiMaterials = new Array();
  23468. /**
  23469. * All of the materials added to this scene
  23470. * @see http://doc.babylonjs.com/babylon101/materials
  23471. */
  23472. this.materials = new Array();
  23473. /**
  23474. * The list of morph target managers added to the scene
  23475. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23476. */
  23477. this.morphTargetManagers = new Array();
  23478. /**
  23479. * The list of geometries used in the scene.
  23480. */
  23481. this.geometries = new Array();
  23482. /**
  23483. * All of the tranform nodes added to this scene
  23484. * @see http://doc.babylonjs.com/how_to/transformnode
  23485. */
  23486. this.transformNodes = new Array();
  23487. /**
  23488. * ActionManagers available on the scene.
  23489. */
  23490. this.actionManagers = new Array();
  23491. /**
  23492. * Sounds to keep.
  23493. */
  23494. this.sounds = new Array();
  23495. /**
  23496. * Textures to keep.
  23497. */
  23498. this.textures = new Array();
  23499. }
  23500. /**
  23501. * Adds a parser in the list of available ones
  23502. * @param name Defines the name of the parser
  23503. * @param parser Defines the parser to add
  23504. */
  23505. AbstractScene.AddParser = function (name, parser) {
  23506. this._BabylonFileParsers[name] = parser;
  23507. };
  23508. /**
  23509. * Gets a general parser from the list of avaialble ones
  23510. * @param name Defines the name of the parser
  23511. * @returns the requested parser or null
  23512. */
  23513. AbstractScene.GetParser = function (name) {
  23514. if (this._BabylonFileParsers[name]) {
  23515. return this._BabylonFileParsers[name];
  23516. }
  23517. return null;
  23518. };
  23519. /**
  23520. * Adds n individual parser in the list of available ones
  23521. * @param name Defines the name of the parser
  23522. * @param parser Defines the parser to add
  23523. */
  23524. AbstractScene.AddIndividualParser = function (name, parser) {
  23525. this._IndividualBabylonFileParsers[name] = parser;
  23526. };
  23527. /**
  23528. * Gets an individual parser from the list of avaialble ones
  23529. * @param name Defines the name of the parser
  23530. * @returns the requested parser or null
  23531. */
  23532. AbstractScene.GetIndividualParser = function (name) {
  23533. if (this._IndividualBabylonFileParsers[name]) {
  23534. return this._IndividualBabylonFileParsers[name];
  23535. }
  23536. return null;
  23537. };
  23538. /**
  23539. * Parser json data and populate both a scene and its associated container object
  23540. * @param jsonData Defines the data to parse
  23541. * @param scene Defines the scene to parse the data for
  23542. * @param container Defines the container attached to the parsing sequence
  23543. * @param rootUrl Defines the root url of the data
  23544. */
  23545. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23546. for (var parserName in this._BabylonFileParsers) {
  23547. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23548. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23549. }
  23550. }
  23551. };
  23552. /**
  23553. * Stores the list of available parsers in the application.
  23554. */
  23555. AbstractScene._BabylonFileParsers = {};
  23556. /**
  23557. * Stores the list of available individual parsers in the application.
  23558. */
  23559. AbstractScene._IndividualBabylonFileParsers = {};
  23560. return AbstractScene;
  23561. }());
  23562. BABYLON.AbstractScene = AbstractScene;
  23563. })(BABYLON || (BABYLON = {}));
  23564. //# sourceMappingURL=babylon.abstractScene.js.map
  23565. var BABYLON;
  23566. (function (BABYLON) {
  23567. /** @hidden */
  23568. var ClickInfo = /** @class */ (function () {
  23569. function ClickInfo() {
  23570. this._singleClick = false;
  23571. this._doubleClick = false;
  23572. this._hasSwiped = false;
  23573. this._ignore = false;
  23574. }
  23575. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23576. get: function () {
  23577. return this._singleClick;
  23578. },
  23579. set: function (b) {
  23580. this._singleClick = b;
  23581. },
  23582. enumerable: true,
  23583. configurable: true
  23584. });
  23585. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23586. get: function () {
  23587. return this._doubleClick;
  23588. },
  23589. set: function (b) {
  23590. this._doubleClick = b;
  23591. },
  23592. enumerable: true,
  23593. configurable: true
  23594. });
  23595. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23596. get: function () {
  23597. return this._hasSwiped;
  23598. },
  23599. set: function (b) {
  23600. this._hasSwiped = b;
  23601. },
  23602. enumerable: true,
  23603. configurable: true
  23604. });
  23605. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23606. get: function () {
  23607. return this._ignore;
  23608. },
  23609. set: function (b) {
  23610. this._ignore = b;
  23611. },
  23612. enumerable: true,
  23613. configurable: true
  23614. });
  23615. return ClickInfo;
  23616. }());
  23617. /**
  23618. * This class is used by the onRenderingGroupObservable
  23619. */
  23620. var RenderingGroupInfo = /** @class */ (function () {
  23621. function RenderingGroupInfo() {
  23622. }
  23623. return RenderingGroupInfo;
  23624. }());
  23625. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23626. /**
  23627. * Represents a scene to be rendered by the engine.
  23628. * @see http://doc.babylonjs.com/features/scene
  23629. */
  23630. var Scene = /** @class */ (function (_super) {
  23631. __extends(Scene, _super);
  23632. /**
  23633. * Creates a new Scene
  23634. * @param engine defines the engine to use to render this scene
  23635. */
  23636. function Scene(engine) {
  23637. var _this = _super.call(this) || this;
  23638. // Members
  23639. /**
  23640. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23641. */
  23642. _this.autoClear = true;
  23643. /**
  23644. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23645. */
  23646. _this.autoClearDepthAndStencil = true;
  23647. /**
  23648. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23649. */
  23650. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23651. /**
  23652. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23653. */
  23654. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23655. _this._forceWireframe = false;
  23656. _this._forcePointsCloud = false;
  23657. /**
  23658. * Gets or sets a boolean indicating if animations are enabled
  23659. */
  23660. _this.animationsEnabled = true;
  23661. _this._animationPropertiesOverride = null;
  23662. /**
  23663. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23664. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23665. */
  23666. _this.useConstantAnimationDeltaTime = false;
  23667. /**
  23668. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23669. * Please note that it requires to run a ray cast through the scene on every frame
  23670. */
  23671. _this.constantlyUpdateMeshUnderPointer = false;
  23672. /**
  23673. * Defines the HTML cursor to use when hovering over interactive elements
  23674. */
  23675. _this.hoverCursor = "pointer";
  23676. /**
  23677. * Defines the HTML default cursor to use (empty by default)
  23678. */
  23679. _this.defaultCursor = "";
  23680. /**
  23681. * This is used to call preventDefault() on pointer down
  23682. * in order to block unwanted artifacts like system double clicks
  23683. */
  23684. _this.preventDefaultOnPointerDown = true;
  23685. // Metadata
  23686. /**
  23687. * Gets or sets user defined metadata
  23688. */
  23689. _this.metadata = null;
  23690. /**
  23691. * Use this array to add regular expressions used to disable offline support for specific urls
  23692. */
  23693. _this.disableOfflineSupportExceptionRules = new Array();
  23694. /**
  23695. * An event triggered when the scene is disposed.
  23696. */
  23697. _this.onDisposeObservable = new BABYLON.Observable();
  23698. _this._onDisposeObserver = null;
  23699. /**
  23700. * An event triggered before rendering the scene (right after animations and physics)
  23701. */
  23702. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23703. _this._onBeforeRenderObserver = null;
  23704. /**
  23705. * An event triggered after rendering the scene
  23706. */
  23707. _this.onAfterRenderObservable = new BABYLON.Observable();
  23708. _this._onAfterRenderObserver = null;
  23709. /**
  23710. * An event triggered before animating the scene
  23711. */
  23712. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23713. /**
  23714. * An event triggered after animations processing
  23715. */
  23716. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23717. /**
  23718. * An event triggered before draw calls are ready to be sent
  23719. */
  23720. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23721. /**
  23722. * An event triggered after draw calls have been sent
  23723. */
  23724. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23725. /**
  23726. * An event triggered when physic simulation is about to be run
  23727. */
  23728. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23729. /**
  23730. * An event triggered when physic simulation has been done
  23731. */
  23732. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23733. /**
  23734. * An event triggered when the scene is ready
  23735. */
  23736. _this.onReadyObservable = new BABYLON.Observable();
  23737. /**
  23738. * An event triggered before rendering a camera
  23739. */
  23740. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23741. _this._onBeforeCameraRenderObserver = null;
  23742. /**
  23743. * An event triggered after rendering a camera
  23744. */
  23745. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23746. _this._onAfterCameraRenderObserver = null;
  23747. /**
  23748. * An event triggered when active meshes evaluation is about to start
  23749. */
  23750. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23751. /**
  23752. * An event triggered when active meshes evaluation is done
  23753. */
  23754. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23755. /**
  23756. * An event triggered when particles rendering is about to start
  23757. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23758. */
  23759. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23760. /**
  23761. * An event triggered when particles rendering is done
  23762. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23763. */
  23764. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23765. /**
  23766. * An event triggered when sprites rendering is about to start
  23767. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23768. */
  23769. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23770. /**
  23771. * An event triggered when sprites rendering is done
  23772. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23773. */
  23774. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23775. /**
  23776. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23777. */
  23778. _this.onDataLoadedObservable = new BABYLON.Observable();
  23779. /**
  23780. * An event triggered when a camera is created
  23781. */
  23782. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23783. /**
  23784. * An event triggered when a camera is removed
  23785. */
  23786. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23787. /**
  23788. * An event triggered when a light is created
  23789. */
  23790. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23791. /**
  23792. * An event triggered when a light is removed
  23793. */
  23794. _this.onLightRemovedObservable = new BABYLON.Observable();
  23795. /**
  23796. * An event triggered when a geometry is created
  23797. */
  23798. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23799. /**
  23800. * An event triggered when a geometry is removed
  23801. */
  23802. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23803. /**
  23804. * An event triggered when a transform node is created
  23805. */
  23806. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23807. /**
  23808. * An event triggered when a transform node is removed
  23809. */
  23810. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23811. /**
  23812. * An event triggered when a mesh is created
  23813. */
  23814. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23815. /**
  23816. * An event triggered when a mesh is removed
  23817. */
  23818. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23819. /**
  23820. * An event triggered when render targets are about to be rendered
  23821. * Can happen multiple times per frame.
  23822. */
  23823. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23824. /**
  23825. * An event triggered when render targets were rendered.
  23826. * Can happen multiple times per frame.
  23827. */
  23828. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23829. /**
  23830. * An event triggered before calculating deterministic simulation step
  23831. */
  23832. _this.onBeforeStepObservable = new BABYLON.Observable();
  23833. /**
  23834. * An event triggered after calculating deterministic simulation step
  23835. */
  23836. _this.onAfterStepObservable = new BABYLON.Observable();
  23837. /**
  23838. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23839. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23840. * 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)
  23841. */
  23842. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23843. /**
  23844. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23845. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23846. * 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)
  23847. */
  23848. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23849. // Animations
  23850. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23851. /**
  23852. * 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).
  23853. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23854. */
  23855. _this.onPrePointerObservable = new BABYLON.Observable();
  23856. /**
  23857. * Observable event triggered each time an input event is received from the rendering canvas
  23858. */
  23859. _this.onPointerObservable = new BABYLON.Observable();
  23860. _this._meshPickProceed = false;
  23861. _this._currentPickResult = null;
  23862. _this._previousPickResult = null;
  23863. _this._totalPointersPressed = 0;
  23864. _this._doubleClickOccured = false;
  23865. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23866. _this.cameraToUseForPointers = null;
  23867. _this._pointerX = 0;
  23868. _this._pointerY = 0;
  23869. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23870. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23871. _this._startingPointerTime = 0;
  23872. _this._previousStartingPointerTime = 0;
  23873. _this._pointerCaptures = {};
  23874. // Deterministic lockstep
  23875. _this._timeAccumulator = 0;
  23876. _this._currentStepId = 0;
  23877. _this._currentInternalStep = 0;
  23878. // Keyboard
  23879. /**
  23880. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23881. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23882. */
  23883. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23884. /**
  23885. * Observable event triggered each time an keyboard event is received from the hosting window
  23886. */
  23887. _this.onKeyboardObservable = new BABYLON.Observable();
  23888. // Coordinates system
  23889. _this._useRightHandedSystem = false;
  23890. // Fog
  23891. _this._fogEnabled = true;
  23892. _this._fogMode = Scene.FOGMODE_NONE;
  23893. /**
  23894. * Gets or sets the fog color to use
  23895. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23896. */
  23897. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23898. /**
  23899. * Gets or sets the fog density to use
  23900. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23901. */
  23902. _this.fogDensity = 0.1;
  23903. /**
  23904. * Gets or sets the fog start distance to use
  23905. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23906. */
  23907. _this.fogStart = 0;
  23908. /**
  23909. * Gets or sets the fog end distance to use
  23910. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23911. */
  23912. _this.fogEnd = 1000.0;
  23913. // Lights
  23914. _this._shadowsEnabled = true;
  23915. _this._lightsEnabled = true;
  23916. /** All of the active cameras added to this scene. */
  23917. _this.activeCameras = new Array();
  23918. // Textures
  23919. _this._texturesEnabled = true;
  23920. // Particles
  23921. /**
  23922. * Gets or sets a boolean indicating if particles are enabled on this scene
  23923. */
  23924. _this.particlesEnabled = true;
  23925. // Sprites
  23926. /**
  23927. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23928. */
  23929. _this.spritesEnabled = true;
  23930. /**
  23931. * All of the sprite managers added to this scene
  23932. * @see http://doc.babylonjs.com/babylon101/sprites
  23933. */
  23934. _this.spriteManagers = new Array();
  23935. // Skeletons
  23936. _this._skeletonsEnabled = true;
  23937. // Lens flares
  23938. /**
  23939. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23940. */
  23941. _this.lensFlaresEnabled = true;
  23942. // Collisions
  23943. /**
  23944. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23945. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23946. */
  23947. _this.collisionsEnabled = true;
  23948. /**
  23949. * Defines the gravity applied to this scene (used only for collisions)
  23950. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23951. */
  23952. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23953. // Postprocesses
  23954. /**
  23955. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23956. */
  23957. _this.postProcessesEnabled = true;
  23958. /**
  23959. * The list of postprocesses added to the scene
  23960. */
  23961. _this.postProcesses = new Array();
  23962. // Customs render targets
  23963. /**
  23964. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23965. */
  23966. _this.renderTargetsEnabled = true;
  23967. /**
  23968. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23969. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23970. */
  23971. _this.dumpNextRenderTargets = false;
  23972. /**
  23973. * The list of user defined render targets added to the scene
  23974. */
  23975. _this.customRenderTargets = new Array();
  23976. /**
  23977. * Gets the list of meshes imported to the scene through SceneLoader
  23978. */
  23979. _this.importedMeshesFiles = new Array();
  23980. // Probes
  23981. /**
  23982. * Gets or sets a boolean indicating if probes are enabled on this scene
  23983. */
  23984. _this.probesEnabled = true;
  23985. /**
  23986. * The list of reflection probes added to the scene
  23987. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23988. */
  23989. _this.reflectionProbes = new Array();
  23990. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23991. // Procedural textures
  23992. /**
  23993. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23994. */
  23995. _this.proceduralTexturesEnabled = true;
  23996. /**
  23997. * The list of procedural textures added to the scene
  23998. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23999. */
  24000. _this.proceduralTextures = new Array();
  24001. /**
  24002. * The list of sound tracks added to the scene
  24003. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24004. */
  24005. _this.soundTracks = new Array();
  24006. _this._audioEnabled = true;
  24007. _this._headphone = false;
  24008. // Performance counters
  24009. _this._totalVertices = new BABYLON.PerfCounter();
  24010. /** @hidden */
  24011. _this._activeIndices = new BABYLON.PerfCounter();
  24012. /** @hidden */
  24013. _this._activeParticles = new BABYLON.PerfCounter();
  24014. /** @hidden */
  24015. _this._activeBones = new BABYLON.PerfCounter();
  24016. _this._animationTime = 0;
  24017. /**
  24018. * Gets or sets a general scale for animation speed
  24019. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24020. */
  24021. _this.animationTimeScale = 1;
  24022. _this._renderId = 0;
  24023. _this._executeWhenReadyTimeoutId = -1;
  24024. _this._intermediateRendering = false;
  24025. _this._viewUpdateFlag = -1;
  24026. _this._projectionUpdateFlag = -1;
  24027. _this._alternateViewUpdateFlag = -1;
  24028. _this._alternateProjectionUpdateFlag = -1;
  24029. /** @hidden */
  24030. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24031. _this._activeRequests = new Array();
  24032. _this._pendingData = new Array();
  24033. _this._isDisposed = false;
  24034. /**
  24035. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24036. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24037. */
  24038. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24039. _this._activeMeshes = new BABYLON.SmartArray(256);
  24040. _this._processedMaterials = new BABYLON.SmartArray(256);
  24041. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24042. /** @hidden */
  24043. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24044. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24045. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24046. /** @hidden */
  24047. _this._activeAnimatables = new Array();
  24048. _this._transformMatrix = BABYLON.Matrix.Zero();
  24049. _this._useAlternateCameraConfiguration = false;
  24050. _this._alternateRendering = false;
  24051. /**
  24052. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24053. * This is useful if there are more lights that the maximum simulteanous authorized
  24054. */
  24055. _this.requireLightSorting = false;
  24056. _this._depthRenderer = {};
  24057. /**
  24058. * Backing store of defined scene components.
  24059. */
  24060. _this._components = [];
  24061. /**
  24062. * Backing store of defined scene components.
  24063. */
  24064. _this._serializableComponents = [];
  24065. /**
  24066. * List of components to register on the next registration step.
  24067. */
  24068. _this._transientComponents = [];
  24069. /**
  24070. * Defines the actions happening before camera updates.
  24071. */
  24072. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24073. /**
  24074. * Defines the actions happening during the per mesh ready checks.
  24075. */
  24076. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24077. /**
  24078. * Defines the actions happening before evaluate active mesh checks.
  24079. */
  24080. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24081. /**
  24082. * Defines the actions happening during the evaluate sub mesh checks.
  24083. */
  24084. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24085. /**
  24086. * Defines the actions happening during the active mesh stage.
  24087. */
  24088. _this._activeMeshStage = BABYLON.Stage.Create();
  24089. /**
  24090. * Defines the actions happening during the per camera render target step.
  24091. */
  24092. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24093. /**
  24094. * Defines the actions happening just before the active camera is drawing.
  24095. */
  24096. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24097. /**
  24098. * Defines the actions happening just before a rendering group is drawing.
  24099. */
  24100. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24101. /**
  24102. * Defines the actions happening just after a rendering group has been drawn.
  24103. */
  24104. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24105. /**
  24106. * Defines the actions happening just after the active camera has been drawn.
  24107. */
  24108. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24109. _this._activeMeshesFrozen = false;
  24110. /** @hidden */
  24111. _this._allowPostProcessClear = true;
  24112. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24113. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24114. _this._engine.scenes.push(_this);
  24115. _this._uid = null;
  24116. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24117. if (BABYLON.PostProcessManager) {
  24118. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24119. }
  24120. if (BABYLON.OutlineRenderer) {
  24121. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24122. }
  24123. if (BABYLON.Tools.IsWindowObjectExist()) {
  24124. _this.attachControl();
  24125. }
  24126. //simplification queue
  24127. if (BABYLON.SimplificationQueue) {
  24128. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24129. }
  24130. //collision coordinator initialization. For now legacy per default.
  24131. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24132. // Uniform Buffer
  24133. _this._createUbo();
  24134. // Default Image processing definition
  24135. if (BABYLON.ImageProcessingConfiguration) {
  24136. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24137. }
  24138. return _this;
  24139. }
  24140. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24141. /** The fog is deactivated */
  24142. get: function () {
  24143. return Scene._FOGMODE_NONE;
  24144. },
  24145. enumerable: true,
  24146. configurable: true
  24147. });
  24148. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24149. /** The fog density is following an exponential function */
  24150. get: function () {
  24151. return Scene._FOGMODE_EXP;
  24152. },
  24153. enumerable: true,
  24154. configurable: true
  24155. });
  24156. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24157. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24158. get: function () {
  24159. return Scene._FOGMODE_EXP2;
  24160. },
  24161. enumerable: true,
  24162. configurable: true
  24163. });
  24164. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24165. /** The fog density is following a linear function. */
  24166. get: function () {
  24167. return Scene._FOGMODE_LINEAR;
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24173. /**
  24174. * Texture used in all pbr material as the reflection texture.
  24175. * As in the majority of the scene they are the same (exception for multi room and so on),
  24176. * this is easier to reference from here than from all the materials.
  24177. */
  24178. get: function () {
  24179. return this._environmentTexture;
  24180. },
  24181. /**
  24182. * Texture used in all pbr material as the reflection texture.
  24183. * As in the majority of the scene they are the same (exception for multi room and so on),
  24184. * this is easier to set here than in all the materials.
  24185. */
  24186. set: function (value) {
  24187. if (this._environmentTexture === value) {
  24188. return;
  24189. }
  24190. this._environmentTexture = value;
  24191. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24192. },
  24193. enumerable: true,
  24194. configurable: true
  24195. });
  24196. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24197. /**
  24198. * Default image processing configuration used either in the rendering
  24199. * Forward main pass or through the imageProcessingPostProcess if present.
  24200. * As in the majority of the scene they are the same (exception for multi camera),
  24201. * this is easier to reference from here than from all the materials and post process.
  24202. *
  24203. * No setter as we it is a shared configuration, you can set the values instead.
  24204. */
  24205. get: function () {
  24206. return this._imageProcessingConfiguration;
  24207. },
  24208. enumerable: true,
  24209. configurable: true
  24210. });
  24211. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24212. get: function () {
  24213. return this._forceWireframe;
  24214. },
  24215. /**
  24216. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24217. */
  24218. set: function (value) {
  24219. if (this._forceWireframe === value) {
  24220. return;
  24221. }
  24222. this._forceWireframe = value;
  24223. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24224. },
  24225. enumerable: true,
  24226. configurable: true
  24227. });
  24228. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24229. get: function () {
  24230. return this._forcePointsCloud;
  24231. },
  24232. /**
  24233. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24234. */
  24235. set: function (value) {
  24236. if (this._forcePointsCloud === value) {
  24237. return;
  24238. }
  24239. this._forcePointsCloud = value;
  24240. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24241. },
  24242. enumerable: true,
  24243. configurable: true
  24244. });
  24245. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24246. /**
  24247. * Gets or sets the animation properties override
  24248. */
  24249. get: function () {
  24250. return this._animationPropertiesOverride;
  24251. },
  24252. set: function (value) {
  24253. this._animationPropertiesOverride = value;
  24254. },
  24255. enumerable: true,
  24256. configurable: true
  24257. });
  24258. Object.defineProperty(Scene.prototype, "onDispose", {
  24259. /** Sets a function to be executed when this scene is disposed. */
  24260. set: function (callback) {
  24261. if (this._onDisposeObserver) {
  24262. this.onDisposeObservable.remove(this._onDisposeObserver);
  24263. }
  24264. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24265. },
  24266. enumerable: true,
  24267. configurable: true
  24268. });
  24269. Object.defineProperty(Scene.prototype, "beforeRender", {
  24270. /** Sets a function to be executed before rendering this scene */
  24271. set: function (callback) {
  24272. if (this._onBeforeRenderObserver) {
  24273. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24274. }
  24275. if (callback) {
  24276. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24277. }
  24278. },
  24279. enumerable: true,
  24280. configurable: true
  24281. });
  24282. Object.defineProperty(Scene.prototype, "afterRender", {
  24283. /** Sets a function to be executed after rendering this scene */
  24284. set: function (callback) {
  24285. if (this._onAfterRenderObserver) {
  24286. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24287. }
  24288. if (callback) {
  24289. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24290. }
  24291. },
  24292. enumerable: true,
  24293. configurable: true
  24294. });
  24295. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24296. /** Sets a function to be executed before rendering a camera*/
  24297. set: function (callback) {
  24298. if (this._onBeforeCameraRenderObserver) {
  24299. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24300. }
  24301. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24302. },
  24303. enumerable: true,
  24304. configurable: true
  24305. });
  24306. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24307. /** Sets a function to be executed after rendering a camera*/
  24308. set: function (callback) {
  24309. if (this._onAfterCameraRenderObserver) {
  24310. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24311. }
  24312. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24313. },
  24314. enumerable: true,
  24315. configurable: true
  24316. });
  24317. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24318. /**
  24319. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24320. */
  24321. get: function () {
  24322. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24323. },
  24324. enumerable: true,
  24325. configurable: true
  24326. });
  24327. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24328. get: function () {
  24329. return this._useRightHandedSystem;
  24330. },
  24331. /**
  24332. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24333. */
  24334. set: function (value) {
  24335. if (this._useRightHandedSystem === value) {
  24336. return;
  24337. }
  24338. this._useRightHandedSystem = value;
  24339. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24340. },
  24341. enumerable: true,
  24342. configurable: true
  24343. });
  24344. /**
  24345. * Sets the step Id used by deterministic lock step
  24346. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24347. * @param newStepId defines the step Id
  24348. */
  24349. Scene.prototype.setStepId = function (newStepId) {
  24350. this._currentStepId = newStepId;
  24351. };
  24352. ;
  24353. /**
  24354. * Gets the step Id used by deterministic lock step
  24355. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24356. * @returns the step Id
  24357. */
  24358. Scene.prototype.getStepId = function () {
  24359. return this._currentStepId;
  24360. };
  24361. ;
  24362. /**
  24363. * Gets the internal step used by deterministic lock step
  24364. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24365. * @returns the internal step
  24366. */
  24367. Scene.prototype.getInternalStep = function () {
  24368. return this._currentInternalStep;
  24369. };
  24370. ;
  24371. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24372. get: function () {
  24373. return this._fogEnabled;
  24374. },
  24375. /**
  24376. * Gets or sets a boolean indicating if fog is enabled on this scene
  24377. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24378. */
  24379. set: function (value) {
  24380. if (this._fogEnabled === value) {
  24381. return;
  24382. }
  24383. this._fogEnabled = value;
  24384. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24385. },
  24386. enumerable: true,
  24387. configurable: true
  24388. });
  24389. Object.defineProperty(Scene.prototype, "fogMode", {
  24390. get: function () {
  24391. return this._fogMode;
  24392. },
  24393. /**
  24394. * Gets or sets the fog mode to use
  24395. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24396. */
  24397. set: function (value) {
  24398. if (this._fogMode === value) {
  24399. return;
  24400. }
  24401. this._fogMode = value;
  24402. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24403. },
  24404. enumerable: true,
  24405. configurable: true
  24406. });
  24407. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24408. get: function () {
  24409. return this._shadowsEnabled;
  24410. },
  24411. /**
  24412. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24413. */
  24414. set: function (value) {
  24415. if (this._shadowsEnabled === value) {
  24416. return;
  24417. }
  24418. this._shadowsEnabled = value;
  24419. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24420. },
  24421. enumerable: true,
  24422. configurable: true
  24423. });
  24424. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24425. get: function () {
  24426. return this._lightsEnabled;
  24427. },
  24428. /**
  24429. * Gets or sets a boolean indicating if lights are enabled on this scene
  24430. */
  24431. set: function (value) {
  24432. if (this._lightsEnabled === value) {
  24433. return;
  24434. }
  24435. this._lightsEnabled = value;
  24436. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24437. },
  24438. enumerable: true,
  24439. configurable: true
  24440. });
  24441. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24442. /** The default material used on meshes when no material is affected */
  24443. get: function () {
  24444. if (!this._defaultMaterial) {
  24445. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24446. }
  24447. return this._defaultMaterial;
  24448. },
  24449. /** The default material used on meshes when no material is affected */
  24450. set: function (value) {
  24451. this._defaultMaterial = value;
  24452. },
  24453. enumerable: true,
  24454. configurable: true
  24455. });
  24456. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24457. get: function () {
  24458. return this._texturesEnabled;
  24459. },
  24460. /**
  24461. * Gets or sets a boolean indicating if textures are enabled on this scene
  24462. */
  24463. set: function (value) {
  24464. if (this._texturesEnabled === value) {
  24465. return;
  24466. }
  24467. this._texturesEnabled = value;
  24468. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24474. get: function () {
  24475. return this._skeletonsEnabled;
  24476. },
  24477. /**
  24478. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24479. */
  24480. set: function (value) {
  24481. if (this._skeletonsEnabled === value) {
  24482. return;
  24483. }
  24484. this._skeletonsEnabled = value;
  24485. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24491. /**
  24492. * Gets the postprocess render pipeline manager
  24493. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24494. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24495. */
  24496. get: function () {
  24497. if (!this._postProcessRenderPipelineManager) {
  24498. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24499. }
  24500. return this._postProcessRenderPipelineManager;
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24506. /**
  24507. * Gets the main soundtrack associated with the scene
  24508. */
  24509. get: function () {
  24510. if (!this._mainSoundTrack) {
  24511. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24512. }
  24513. return this._mainSoundTrack;
  24514. },
  24515. enumerable: true,
  24516. configurable: true
  24517. });
  24518. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24519. /** @hidden */
  24520. get: function () {
  24521. return this._alternateRendering;
  24522. },
  24523. enumerable: true,
  24524. configurable: true
  24525. });
  24526. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24527. /**
  24528. * Gets the list of frustum planes (built from the active camera)
  24529. */
  24530. get: function () {
  24531. return this._frustumPlanes;
  24532. },
  24533. enumerable: true,
  24534. configurable: true
  24535. });
  24536. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24537. /**
  24538. * Gets the current geometry buffer associated to the scene.
  24539. */
  24540. get: function () {
  24541. return this._geometryBufferRenderer;
  24542. },
  24543. /**
  24544. * Sets the current geometry buffer for the scene.
  24545. */
  24546. set: function (geometryBufferRenderer) {
  24547. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24548. this._geometryBufferRenderer = geometryBufferRenderer;
  24549. }
  24550. },
  24551. enumerable: true,
  24552. configurable: true
  24553. });
  24554. /**
  24555. * Registers the transient components if needed.
  24556. */
  24557. Scene.prototype._registerTransientComponents = function () {
  24558. // Register components that have been associated lately to the scene.
  24559. if (this._transientComponents.length > 0) {
  24560. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24561. var component = _a[_i];
  24562. component.register();
  24563. }
  24564. this._transientComponents = [];
  24565. }
  24566. };
  24567. /**
  24568. * Add a component to the scene.
  24569. * Note that the ccomponent could be registered on th next frame if this is called after
  24570. * the register component stage.
  24571. * @param component Defines the component to add to the scene
  24572. */
  24573. Scene.prototype._addComponent = function (component) {
  24574. this._components.push(component);
  24575. this._transientComponents.push(component);
  24576. var serializableComponent = component;
  24577. if (serializableComponent.addFromContainer) {
  24578. this._serializableComponents.push(serializableComponent);
  24579. }
  24580. };
  24581. /**
  24582. * Gets a component from the scene.
  24583. * @param name defines the name of the component to retrieve
  24584. * @returns the component or null if not present
  24585. */
  24586. Scene.prototype._getComponent = function (name) {
  24587. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24588. var component = _a[_i];
  24589. if (component.name === name) {
  24590. return component;
  24591. }
  24592. }
  24593. return null;
  24594. };
  24595. Object.defineProperty(Scene.prototype, "debugLayer", {
  24596. /**
  24597. * Gets the debug layer (aka Inspector) associated with the scene
  24598. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24599. */
  24600. get: function () {
  24601. if (!this._debugLayer) {
  24602. this._debugLayer = new BABYLON.DebugLayer(this);
  24603. }
  24604. return this._debugLayer;
  24605. },
  24606. enumerable: true,
  24607. configurable: true
  24608. });
  24609. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24610. /**
  24611. * Gets a boolean indicating if collisions are processed on a web worker
  24612. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24613. */
  24614. get: function () {
  24615. return this._workerCollisions;
  24616. },
  24617. set: function (enabled) {
  24618. if (!BABYLON.CollisionCoordinatorLegacy) {
  24619. return;
  24620. }
  24621. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24622. this._workerCollisions = enabled;
  24623. if (this.collisionCoordinator) {
  24624. this.collisionCoordinator.destroy();
  24625. }
  24626. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24627. this.collisionCoordinator.init(this);
  24628. },
  24629. enumerable: true,
  24630. configurable: true
  24631. });
  24632. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24633. /**
  24634. * Gets the octree used to boost mesh selection (picking)
  24635. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24636. */
  24637. get: function () {
  24638. return this._selectionOctree;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24644. /**
  24645. * Gets the mesh that is currently under the pointer
  24646. */
  24647. get: function () {
  24648. return this._pointerOverMesh;
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. Object.defineProperty(Scene.prototype, "pointerX", {
  24654. /**
  24655. * Gets the current on-screen X position of the pointer
  24656. */
  24657. get: function () {
  24658. return this._pointerX;
  24659. },
  24660. enumerable: true,
  24661. configurable: true
  24662. });
  24663. Object.defineProperty(Scene.prototype, "pointerY", {
  24664. /**
  24665. * Gets the current on-screen Y position of the pointer
  24666. */
  24667. get: function () {
  24668. return this._pointerY;
  24669. },
  24670. enumerable: true,
  24671. configurable: true
  24672. });
  24673. /**
  24674. * Gets the cached material (ie. the latest rendered one)
  24675. * @returns the cached material
  24676. */
  24677. Scene.prototype.getCachedMaterial = function () {
  24678. return this._cachedMaterial;
  24679. };
  24680. /**
  24681. * Gets the cached effect (ie. the latest rendered one)
  24682. * @returns the cached effect
  24683. */
  24684. Scene.prototype.getCachedEffect = function () {
  24685. return this._cachedEffect;
  24686. };
  24687. /**
  24688. * Gets the cached visibility state (ie. the latest rendered one)
  24689. * @returns the cached visibility state
  24690. */
  24691. Scene.prototype.getCachedVisibility = function () {
  24692. return this._cachedVisibility;
  24693. };
  24694. /**
  24695. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24696. * @param material defines the current material
  24697. * @param effect defines the current effect
  24698. * @param visibility defines the current visibility state
  24699. * @returns true if one parameter is not cached
  24700. */
  24701. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24702. if (visibility === void 0) { visibility = 1; }
  24703. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24704. };
  24705. /**
  24706. * Gets the outline renderer associated with the scene
  24707. * @returns a OutlineRenderer
  24708. */
  24709. Scene.prototype.getOutlineRenderer = function () {
  24710. return this._outlineRenderer;
  24711. };
  24712. /**
  24713. * Gets the engine associated with the scene
  24714. * @returns an Engine
  24715. */
  24716. Scene.prototype.getEngine = function () {
  24717. return this._engine;
  24718. };
  24719. /**
  24720. * Gets the total number of vertices rendered per frame
  24721. * @returns the total number of vertices rendered per frame
  24722. */
  24723. Scene.prototype.getTotalVertices = function () {
  24724. return this._totalVertices.current;
  24725. };
  24726. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24727. /**
  24728. * Gets the performance counter for total vertices
  24729. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24730. */
  24731. get: function () {
  24732. return this._totalVertices;
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. /**
  24738. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24739. * @returns the total number of active indices rendered per frame
  24740. */
  24741. Scene.prototype.getActiveIndices = function () {
  24742. return this._activeIndices.current;
  24743. };
  24744. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24745. /**
  24746. * Gets the performance counter for active indices
  24747. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24748. */
  24749. get: function () {
  24750. return this._activeIndices;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. /**
  24756. * Gets the total number of active particles rendered per frame
  24757. * @returns the total number of active particles rendered per frame
  24758. */
  24759. Scene.prototype.getActiveParticles = function () {
  24760. return this._activeParticles.current;
  24761. };
  24762. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24763. /**
  24764. * Gets the performance counter for active particles
  24765. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24766. */
  24767. get: function () {
  24768. return this._activeParticles;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. /**
  24774. * Gets the total number of active bones rendered per frame
  24775. * @returns the total number of active bones rendered per frame
  24776. */
  24777. Scene.prototype.getActiveBones = function () {
  24778. return this._activeBones.current;
  24779. };
  24780. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24781. /**
  24782. * Gets the performance counter for active bones
  24783. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24784. */
  24785. get: function () {
  24786. return this._activeBones;
  24787. },
  24788. enumerable: true,
  24789. configurable: true
  24790. });
  24791. /** @hidden */
  24792. Scene.prototype.getInterFramePerfCounter = function () {
  24793. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24794. return 0;
  24795. };
  24796. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24797. /** @hidden */
  24798. get: function () {
  24799. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24800. return null;
  24801. },
  24802. enumerable: true,
  24803. configurable: true
  24804. });
  24805. /** @hidden */
  24806. Scene.prototype.getLastFrameDuration = function () {
  24807. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24808. return 0;
  24809. };
  24810. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24811. /** @hidden */
  24812. get: function () {
  24813. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24814. return null;
  24815. },
  24816. enumerable: true,
  24817. configurable: true
  24818. });
  24819. /** @hidden */
  24820. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24821. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24822. return 0;
  24823. };
  24824. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24825. /** @hidden */
  24826. get: function () {
  24827. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24828. return null;
  24829. },
  24830. enumerable: true,
  24831. configurable: true
  24832. });
  24833. /**
  24834. * Gets the array of active meshes
  24835. * @returns an array of AbstractMesh
  24836. */
  24837. Scene.prototype.getActiveMeshes = function () {
  24838. return this._activeMeshes;
  24839. };
  24840. /** @hidden */
  24841. Scene.prototype.getRenderTargetsDuration = function () {
  24842. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24843. return 0;
  24844. };
  24845. /** @hidden */
  24846. Scene.prototype.getRenderDuration = function () {
  24847. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24848. return 0;
  24849. };
  24850. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24851. /** @hidden */
  24852. get: function () {
  24853. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24854. return null;
  24855. },
  24856. enumerable: true,
  24857. configurable: true
  24858. });
  24859. /** @hidden */
  24860. Scene.prototype.getParticlesDuration = function () {
  24861. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24862. return 0;
  24863. };
  24864. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24865. /** @hidden */
  24866. get: function () {
  24867. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24868. return null;
  24869. },
  24870. enumerable: true,
  24871. configurable: true
  24872. });
  24873. /** @hidden */
  24874. Scene.prototype.getSpritesDuration = function () {
  24875. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24876. return 0;
  24877. };
  24878. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24879. /** @hidden */
  24880. get: function () {
  24881. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24882. return null;
  24883. },
  24884. enumerable: true,
  24885. configurable: true
  24886. });
  24887. /**
  24888. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24889. * @returns a number
  24890. */
  24891. Scene.prototype.getAnimationRatio = function () {
  24892. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24893. };
  24894. /**
  24895. * Gets an unique Id for the current frame
  24896. * @returns a number
  24897. */
  24898. Scene.prototype.getRenderId = function () {
  24899. return this._renderId;
  24900. };
  24901. /** Call this function if you want to manually increment the render Id*/
  24902. Scene.prototype.incrementRenderId = function () {
  24903. this._renderId++;
  24904. };
  24905. Scene.prototype._updatePointerPosition = function (evt) {
  24906. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24907. if (!canvasRect) {
  24908. return;
  24909. }
  24910. this._pointerX = evt.clientX - canvasRect.left;
  24911. this._pointerY = evt.clientY - canvasRect.top;
  24912. this._unTranslatedPointerX = this._pointerX;
  24913. this._unTranslatedPointerY = this._pointerY;
  24914. };
  24915. Scene.prototype._createUbo = function () {
  24916. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24917. this._sceneUbo.addUniform("viewProjection", 16);
  24918. this._sceneUbo.addUniform("view", 16);
  24919. };
  24920. Scene.prototype._createAlternateUbo = function () {
  24921. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24922. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24923. this._alternateSceneUbo.addUniform("view", 16);
  24924. };
  24925. // Pointers handling
  24926. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24927. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24928. if (result) {
  24929. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24930. }
  24931. return result;
  24932. };
  24933. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24934. if (pointerInfo.pickInfo) {
  24935. if (!pointerInfo.pickInfo.ray) {
  24936. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24937. }
  24938. }
  24939. };
  24940. /**
  24941. * Use this method to simulate a pointer move on a mesh
  24942. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24943. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24944. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24945. * @returns the current scene
  24946. */
  24947. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24948. var evt = new PointerEvent("pointermove", pointerEventInit);
  24949. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24950. return this;
  24951. }
  24952. return this._processPointerMove(pickResult, evt);
  24953. };
  24954. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24955. var canvas = this._engine.getRenderingCanvas();
  24956. if (!canvas) {
  24957. return this;
  24958. }
  24959. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24960. this.setPointerOverSprite(null);
  24961. this.setPointerOverMesh(pickResult.pickedMesh);
  24962. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24963. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24964. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24965. }
  24966. else {
  24967. canvas.style.cursor = this.hoverCursor;
  24968. }
  24969. }
  24970. else {
  24971. canvas.style.cursor = this.defaultCursor;
  24972. }
  24973. }
  24974. else {
  24975. this.setPointerOverMesh(null);
  24976. // Sprites
  24977. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24978. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24979. this.setPointerOverSprite(pickResult.pickedSprite);
  24980. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24981. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24982. }
  24983. else {
  24984. canvas.style.cursor = this.hoverCursor;
  24985. }
  24986. }
  24987. else {
  24988. this.setPointerOverSprite(null);
  24989. // Restore pointer
  24990. canvas.style.cursor = this.defaultCursor;
  24991. }
  24992. }
  24993. if (pickResult) {
  24994. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24995. if (this.onPointerMove) {
  24996. this.onPointerMove(evt, pickResult, type);
  24997. }
  24998. if (this.onPointerObservable.hasObservers()) {
  24999. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25000. this._setRayOnPointerInfo(pi);
  25001. this.onPointerObservable.notifyObservers(pi, type);
  25002. }
  25003. }
  25004. return this;
  25005. };
  25006. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25007. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25008. if (pickResult) {
  25009. pi.ray = pickResult.ray;
  25010. }
  25011. this.onPrePointerObservable.notifyObservers(pi, type);
  25012. if (pi.skipOnPointerObservable) {
  25013. return true;
  25014. }
  25015. else {
  25016. return false;
  25017. }
  25018. };
  25019. /**
  25020. * Use this method to simulate a pointer down on a mesh
  25021. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25022. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25023. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25024. * @returns the current scene
  25025. */
  25026. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25027. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25028. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25029. return this;
  25030. }
  25031. return this._processPointerDown(pickResult, evt);
  25032. };
  25033. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25034. var _this = this;
  25035. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25036. this._pickedDownMesh = pickResult.pickedMesh;
  25037. var actionManager = pickResult.pickedMesh.actionManager;
  25038. if (actionManager) {
  25039. if (actionManager.hasPickTriggers) {
  25040. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25041. switch (evt.button) {
  25042. case 0:
  25043. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25044. break;
  25045. case 1:
  25046. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25047. break;
  25048. case 2:
  25049. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25050. break;
  25051. }
  25052. }
  25053. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25054. window.setTimeout(function () {
  25055. 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);
  25056. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25057. if (_this._totalPointersPressed !== 0 &&
  25058. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25059. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25060. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25061. _this._startingPointerTime = 0;
  25062. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25063. }
  25064. }
  25065. }, Scene.LongPressDelay);
  25066. }
  25067. }
  25068. }
  25069. if (pickResult) {
  25070. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25071. if (this.onPointerDown) {
  25072. this.onPointerDown(evt, pickResult, type);
  25073. }
  25074. if (this.onPointerObservable.hasObservers()) {
  25075. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25076. this._setRayOnPointerInfo(pi);
  25077. this.onPointerObservable.notifyObservers(pi, type);
  25078. }
  25079. }
  25080. return this;
  25081. };
  25082. /**
  25083. * Use this method to simulate a pointer up on a mesh
  25084. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25085. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25086. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25087. * @returns the current scene
  25088. */
  25089. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25090. var evt = new PointerEvent("pointerup", pointerEventInit);
  25091. var clickInfo = new ClickInfo();
  25092. clickInfo.singleClick = true;
  25093. clickInfo.ignore = true;
  25094. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25095. return this;
  25096. }
  25097. return this._processPointerUp(pickResult, evt, clickInfo);
  25098. };
  25099. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25100. if (pickResult && pickResult && pickResult.pickedMesh) {
  25101. this._pickedUpMesh = pickResult.pickedMesh;
  25102. if (this._pickedDownMesh === this._pickedUpMesh) {
  25103. if (this.onPointerPick) {
  25104. this.onPointerPick(evt, pickResult);
  25105. }
  25106. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25107. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25108. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25109. this._setRayOnPointerInfo(pi);
  25110. this.onPointerObservable.notifyObservers(pi, type_1);
  25111. }
  25112. }
  25113. if (pickResult.pickedMesh.actionManager) {
  25114. if (clickInfo.ignore) {
  25115. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25116. }
  25117. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25118. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25119. }
  25120. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25121. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25122. }
  25123. }
  25124. }
  25125. if (this._pickedDownMesh &&
  25126. this._pickedDownMesh.actionManager &&
  25127. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25128. this._pickedDownMesh !== this._pickedUpMesh) {
  25129. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25130. }
  25131. var type = BABYLON.PointerEventTypes.POINTERUP;
  25132. if (this.onPointerObservable.hasObservers()) {
  25133. if (!clickInfo.ignore) {
  25134. if (!clickInfo.hasSwiped) {
  25135. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25136. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25137. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25138. this._setRayOnPointerInfo(pi);
  25139. this.onPointerObservable.notifyObservers(pi, type_2);
  25140. }
  25141. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25142. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25143. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25144. this._setRayOnPointerInfo(pi);
  25145. this.onPointerObservable.notifyObservers(pi, type_3);
  25146. }
  25147. }
  25148. }
  25149. else {
  25150. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25151. this._setRayOnPointerInfo(pi);
  25152. this.onPointerObservable.notifyObservers(pi, type);
  25153. }
  25154. }
  25155. if (this.onPointerUp) {
  25156. this.onPointerUp(evt, pickResult, type);
  25157. }
  25158. return this;
  25159. };
  25160. /**
  25161. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25162. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25163. * @returns true if the pointer was captured
  25164. */
  25165. Scene.prototype.isPointerCaptured = function (pointerId) {
  25166. if (pointerId === void 0) { pointerId = 0; }
  25167. return this._pointerCaptures[pointerId];
  25168. };
  25169. /**
  25170. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25171. * @param attachUp defines if you want to attach events to pointerup
  25172. * @param attachDown defines if you want to attach events to pointerdown
  25173. * @param attachMove defines if you want to attach events to pointermove
  25174. */
  25175. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25176. var _this = this;
  25177. if (attachUp === void 0) { attachUp = true; }
  25178. if (attachDown === void 0) { attachDown = true; }
  25179. if (attachMove === void 0) { attachMove = true; }
  25180. this._initActionManager = function (act, clickInfo) {
  25181. if (!_this._meshPickProceed) {
  25182. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25183. _this._currentPickResult = pickResult;
  25184. if (pickResult) {
  25185. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25186. }
  25187. _this._meshPickProceed = true;
  25188. }
  25189. return act;
  25190. };
  25191. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25192. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25193. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25194. btn !== _this._previousButtonPressed) {
  25195. _this._doubleClickOccured = false;
  25196. clickInfo.singleClick = true;
  25197. clickInfo.ignore = false;
  25198. cb(clickInfo, _this._currentPickResult);
  25199. }
  25200. };
  25201. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25202. var clickInfo = new ClickInfo();
  25203. _this._currentPickResult = null;
  25204. var act = null;
  25205. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25206. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25207. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25208. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25209. act = _this._initActionManager(act, clickInfo);
  25210. if (act)
  25211. checkPicking = act.hasPickTriggers;
  25212. }
  25213. if (checkPicking) {
  25214. var btn = evt.button;
  25215. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25216. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25217. if (!clickInfo.hasSwiped) {
  25218. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25219. if (!checkSingleClickImmediately) {
  25220. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25221. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25222. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25223. act = _this._initActionManager(act, clickInfo);
  25224. if (act)
  25225. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25226. }
  25227. }
  25228. if (checkSingleClickImmediately) {
  25229. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25230. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25231. btn !== _this._previousButtonPressed) {
  25232. clickInfo.singleClick = true;
  25233. cb(clickInfo, _this._currentPickResult);
  25234. }
  25235. }
  25236. // at least one double click is required to be check and exclusive double click is enabled
  25237. else {
  25238. // wait that no double click has been raised during the double click delay
  25239. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25240. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25241. }
  25242. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25243. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25244. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25245. act = _this._initActionManager(act, clickInfo);
  25246. if (act)
  25247. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25248. }
  25249. if (checkDoubleClick) {
  25250. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25251. if (btn === _this._previousButtonPressed &&
  25252. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25253. !_this._doubleClickOccured) {
  25254. // pointer has not moved for 2 clicks, it's a double click
  25255. if (!clickInfo.hasSwiped &&
  25256. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25257. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25258. _this._previousStartingPointerTime = 0;
  25259. _this._doubleClickOccured = true;
  25260. clickInfo.doubleClick = true;
  25261. clickInfo.ignore = false;
  25262. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25263. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25264. }
  25265. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25266. cb(clickInfo, _this._currentPickResult);
  25267. }
  25268. // if the two successive clicks are too far, it's just two simple clicks
  25269. else {
  25270. _this._doubleClickOccured = false;
  25271. _this._previousStartingPointerTime = _this._startingPointerTime;
  25272. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25273. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25274. _this._previousButtonPressed = btn;
  25275. if (Scene.ExclusiveDoubleClickMode) {
  25276. if (_this._previousDelayedSimpleClickTimeout) {
  25277. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25278. }
  25279. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25280. cb(clickInfo, _this._previousPickResult);
  25281. }
  25282. else {
  25283. cb(clickInfo, _this._currentPickResult);
  25284. }
  25285. }
  25286. }
  25287. // just the first click of the double has been raised
  25288. else {
  25289. _this._doubleClickOccured = false;
  25290. _this._previousStartingPointerTime = _this._startingPointerTime;
  25291. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25292. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25293. _this._previousButtonPressed = btn;
  25294. }
  25295. }
  25296. }
  25297. }
  25298. clickInfo.ignore = true;
  25299. cb(clickInfo, _this._currentPickResult);
  25300. };
  25301. this._spritePredicate = function (sprite) {
  25302. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25303. };
  25304. this._onPointerMove = function (evt) {
  25305. _this._updatePointerPosition(evt);
  25306. // PreObservable support
  25307. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25308. return;
  25309. }
  25310. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25311. return;
  25312. }
  25313. if (!_this.pointerMovePredicate) {
  25314. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25315. }
  25316. // Meshes
  25317. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25318. _this._processPointerMove(pickResult, evt);
  25319. };
  25320. this._onPointerDown = function (evt) {
  25321. _this._totalPointersPressed++;
  25322. _this._pickedDownMesh = null;
  25323. _this._meshPickProceed = false;
  25324. _this._updatePointerPosition(evt);
  25325. if (_this.preventDefaultOnPointerDown && canvas) {
  25326. evt.preventDefault();
  25327. canvas.focus();
  25328. }
  25329. // PreObservable support
  25330. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25331. return;
  25332. }
  25333. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25334. return;
  25335. }
  25336. _this._pointerCaptures[evt.pointerId] = true;
  25337. _this._startingPointerPosition.x = _this._pointerX;
  25338. _this._startingPointerPosition.y = _this._pointerY;
  25339. _this._startingPointerTime = Date.now();
  25340. if (!_this.pointerDownPredicate) {
  25341. _this.pointerDownPredicate = function (mesh) {
  25342. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25343. };
  25344. }
  25345. // Meshes
  25346. _this._pickedDownMesh = null;
  25347. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25348. _this._processPointerDown(pickResult, evt);
  25349. // Sprites
  25350. _this._pickedDownSprite = null;
  25351. if (_this.spriteManagers.length > 0) {
  25352. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25353. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25354. if (pickResult.pickedSprite.actionManager) {
  25355. _this._pickedDownSprite = pickResult.pickedSprite;
  25356. switch (evt.button) {
  25357. case 0:
  25358. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25359. break;
  25360. case 1:
  25361. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25362. break;
  25363. case 2:
  25364. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25365. break;
  25366. }
  25367. if (pickResult.pickedSprite.actionManager) {
  25368. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25369. }
  25370. }
  25371. }
  25372. }
  25373. };
  25374. this._onPointerUp = function (evt) {
  25375. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25376. return; // So we need to test it the pointer down was pressed before.
  25377. }
  25378. _this._totalPointersPressed--;
  25379. _this._pickedUpMesh = null;
  25380. _this._meshPickProceed = false;
  25381. _this._updatePointerPosition(evt);
  25382. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25383. // PreObservable support
  25384. if (_this.onPrePointerObservable.hasObservers()) {
  25385. if (!clickInfo.ignore) {
  25386. if (!clickInfo.hasSwiped) {
  25387. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25388. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25389. return;
  25390. }
  25391. }
  25392. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25393. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25394. return;
  25395. }
  25396. }
  25397. }
  25398. }
  25399. else {
  25400. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25401. return;
  25402. }
  25403. }
  25404. }
  25405. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25406. return;
  25407. }
  25408. _this._pointerCaptures[evt.pointerId] = false;
  25409. if (!_this.pointerUpPredicate) {
  25410. _this.pointerUpPredicate = function (mesh) {
  25411. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25412. };
  25413. }
  25414. // Meshes
  25415. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25416. _this._initActionManager(null, clickInfo);
  25417. }
  25418. if (!pickResult) {
  25419. pickResult = _this._currentPickResult;
  25420. }
  25421. _this._processPointerUp(pickResult, evt, clickInfo);
  25422. // Sprites
  25423. if (!clickInfo.ignore) {
  25424. if (_this.spriteManagers.length > 0) {
  25425. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25426. if (spritePickResult) {
  25427. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25428. if (spritePickResult.pickedSprite.actionManager) {
  25429. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25430. if (spritePickResult.pickedSprite.actionManager) {
  25431. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25432. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25433. }
  25434. }
  25435. }
  25436. }
  25437. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25438. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25439. }
  25440. }
  25441. }
  25442. }
  25443. _this._previousPickResult = _this._currentPickResult;
  25444. });
  25445. };
  25446. this._onKeyDown = function (evt) {
  25447. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25448. if (_this.onPreKeyboardObservable.hasObservers()) {
  25449. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25450. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25451. if (pi.skipOnPointerObservable) {
  25452. return;
  25453. }
  25454. }
  25455. if (_this.onKeyboardObservable.hasObservers()) {
  25456. var pi = new BABYLON.KeyboardInfo(type, evt);
  25457. _this.onKeyboardObservable.notifyObservers(pi, type);
  25458. }
  25459. if (_this.actionManager) {
  25460. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25461. }
  25462. };
  25463. this._onKeyUp = function (evt) {
  25464. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25465. if (_this.onPreKeyboardObservable.hasObservers()) {
  25466. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25467. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25468. if (pi.skipOnPointerObservable) {
  25469. return;
  25470. }
  25471. }
  25472. if (_this.onKeyboardObservable.hasObservers()) {
  25473. var pi = new BABYLON.KeyboardInfo(type, evt);
  25474. _this.onKeyboardObservable.notifyObservers(pi, type);
  25475. }
  25476. if (_this.actionManager) {
  25477. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25478. }
  25479. };
  25480. var engine = this.getEngine();
  25481. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25482. if (!canvas) {
  25483. return;
  25484. }
  25485. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25486. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25487. });
  25488. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25489. if (!canvas) {
  25490. return;
  25491. }
  25492. canvas.removeEventListener("keydown", _this._onKeyDown);
  25493. canvas.removeEventListener("keyup", _this._onKeyUp);
  25494. });
  25495. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25496. var canvas = this._engine.getRenderingCanvas();
  25497. if (!canvas) {
  25498. return;
  25499. }
  25500. if (attachMove) {
  25501. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25502. // Wheel
  25503. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25504. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25505. }
  25506. if (attachDown) {
  25507. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25508. }
  25509. if (attachUp) {
  25510. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25511. }
  25512. canvas.tabIndex = 1;
  25513. };
  25514. /** Detaches all event handlers*/
  25515. Scene.prototype.detachControl = function () {
  25516. var engine = this.getEngine();
  25517. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25518. var canvas = engine.getRenderingCanvas();
  25519. if (!canvas) {
  25520. return;
  25521. }
  25522. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25523. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25524. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25525. if (this._onCanvasBlurObserver) {
  25526. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25527. }
  25528. if (this._onCanvasFocusObserver) {
  25529. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25530. }
  25531. // Wheel
  25532. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25533. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25534. // Keyboard
  25535. canvas.removeEventListener("keydown", this._onKeyDown);
  25536. canvas.removeEventListener("keyup", this._onKeyUp);
  25537. // Observables
  25538. this.onKeyboardObservable.clear();
  25539. this.onPreKeyboardObservable.clear();
  25540. this.onPointerObservable.clear();
  25541. this.onPrePointerObservable.clear();
  25542. };
  25543. /**
  25544. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25545. * Delay loaded resources are not taking in account
  25546. * @return true if all required resources are ready
  25547. */
  25548. Scene.prototype.isReady = function () {
  25549. if (this._isDisposed) {
  25550. return false;
  25551. }
  25552. if (this._pendingData.length > 0) {
  25553. return false;
  25554. }
  25555. var index;
  25556. var engine = this.getEngine();
  25557. // Geometries
  25558. for (index = 0; index < this.geometries.length; index++) {
  25559. var geometry = this.geometries[index];
  25560. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25561. return false;
  25562. }
  25563. }
  25564. // Meshes
  25565. for (index = 0; index < this.meshes.length; index++) {
  25566. var mesh = this.meshes[index];
  25567. if (!mesh.isEnabled()) {
  25568. continue;
  25569. }
  25570. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25571. continue;
  25572. }
  25573. if (!mesh.isReady(true)) {
  25574. return false;
  25575. }
  25576. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25577. // Is Ready For Mesh
  25578. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25579. var step = _a[_i];
  25580. if (!step.action(mesh, hardwareInstancedRendering)) {
  25581. return false;
  25582. }
  25583. }
  25584. }
  25585. // Post-processes
  25586. if (this.activeCameras && this.activeCameras.length > 0) {
  25587. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25588. var camera = _c[_b];
  25589. if (!camera.isReady(true)) {
  25590. return false;
  25591. }
  25592. }
  25593. }
  25594. else if (this.activeCamera) {
  25595. if (!this.activeCamera.isReady(true)) {
  25596. return false;
  25597. }
  25598. }
  25599. // Particles
  25600. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25601. var particleSystem = _e[_d];
  25602. if (!particleSystem.isReady()) {
  25603. return false;
  25604. }
  25605. }
  25606. return true;
  25607. };
  25608. /** Resets all cached information relative to material (including effect and visibility) */
  25609. Scene.prototype.resetCachedMaterial = function () {
  25610. this._cachedMaterial = null;
  25611. this._cachedEffect = null;
  25612. this._cachedVisibility = null;
  25613. };
  25614. /**
  25615. * Registers a function to be called before every frame render
  25616. * @param func defines the function to register
  25617. */
  25618. Scene.prototype.registerBeforeRender = function (func) {
  25619. this.onBeforeRenderObservable.add(func);
  25620. };
  25621. /**
  25622. * Unregisters a function called before every frame render
  25623. * @param func defines the function to unregister
  25624. */
  25625. Scene.prototype.unregisterBeforeRender = function (func) {
  25626. this.onBeforeRenderObservable.removeCallback(func);
  25627. };
  25628. /**
  25629. * Registers a function to be called after every frame render
  25630. * @param func defines the function to register
  25631. */
  25632. Scene.prototype.registerAfterRender = function (func) {
  25633. this.onAfterRenderObservable.add(func);
  25634. };
  25635. /**
  25636. * Unregisters a function called after every frame render
  25637. * @param func defines the function to unregister
  25638. */
  25639. Scene.prototype.unregisterAfterRender = function (func) {
  25640. this.onAfterRenderObservable.removeCallback(func);
  25641. };
  25642. Scene.prototype._executeOnceBeforeRender = function (func) {
  25643. var _this = this;
  25644. var execFunc = function () {
  25645. func();
  25646. setTimeout(function () {
  25647. _this.unregisterBeforeRender(execFunc);
  25648. });
  25649. };
  25650. this.registerBeforeRender(execFunc);
  25651. };
  25652. /**
  25653. * The provided function will run before render once and will be disposed afterwards.
  25654. * A timeout delay can be provided so that the function will be executed in N ms.
  25655. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25656. * @param func The function to be executed.
  25657. * @param timeout optional delay in ms
  25658. */
  25659. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25660. var _this = this;
  25661. if (timeout !== undefined) {
  25662. setTimeout(function () {
  25663. _this._executeOnceBeforeRender(func);
  25664. }, timeout);
  25665. }
  25666. else {
  25667. this._executeOnceBeforeRender(func);
  25668. }
  25669. };
  25670. /** @hidden */
  25671. Scene.prototype._addPendingData = function (data) {
  25672. this._pendingData.push(data);
  25673. };
  25674. /** @hidden */
  25675. Scene.prototype._removePendingData = function (data) {
  25676. var wasLoading = this.isLoading;
  25677. var index = this._pendingData.indexOf(data);
  25678. if (index !== -1) {
  25679. this._pendingData.splice(index, 1);
  25680. }
  25681. if (wasLoading && !this.isLoading) {
  25682. this.onDataLoadedObservable.notifyObservers(this);
  25683. }
  25684. };
  25685. /**
  25686. * Returns the number of items waiting to be loaded
  25687. * @returns the number of items waiting to be loaded
  25688. */
  25689. Scene.prototype.getWaitingItemsCount = function () {
  25690. return this._pendingData.length;
  25691. };
  25692. Object.defineProperty(Scene.prototype, "isLoading", {
  25693. /**
  25694. * Returns a boolean indicating if the scene is still loading data
  25695. */
  25696. get: function () {
  25697. return this._pendingData.length > 0;
  25698. },
  25699. enumerable: true,
  25700. configurable: true
  25701. });
  25702. /**
  25703. * Registers a function to be executed when the scene is ready
  25704. * @param {Function} func - the function to be executed
  25705. */
  25706. Scene.prototype.executeWhenReady = function (func) {
  25707. var _this = this;
  25708. this.onReadyObservable.add(func);
  25709. if (this._executeWhenReadyTimeoutId !== -1) {
  25710. return;
  25711. }
  25712. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25713. _this._checkIsReady();
  25714. }, 150);
  25715. };
  25716. /**
  25717. * Returns a promise that resolves when the scene is ready
  25718. * @returns A promise that resolves when the scene is ready
  25719. */
  25720. Scene.prototype.whenReadyAsync = function () {
  25721. var _this = this;
  25722. return new Promise(function (resolve) {
  25723. _this.executeWhenReady(function () {
  25724. resolve();
  25725. });
  25726. });
  25727. };
  25728. /** @hidden */
  25729. Scene.prototype._checkIsReady = function () {
  25730. var _this = this;
  25731. this._registerTransientComponents();
  25732. if (this.isReady()) {
  25733. this.onReadyObservable.notifyObservers(this);
  25734. this.onReadyObservable.clear();
  25735. this._executeWhenReadyTimeoutId = -1;
  25736. return;
  25737. }
  25738. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25739. _this._checkIsReady();
  25740. }, 150);
  25741. };
  25742. // Animations
  25743. /**
  25744. * Will start the animation sequence of a given target
  25745. * @param target defines the target
  25746. * @param from defines from which frame should animation start
  25747. * @param to defines until which frame should animation run.
  25748. * @param weight defines the weight to apply to the animation (1.0 by default)
  25749. * @param loop defines if the animation loops
  25750. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25751. * @param onAnimationEnd defines the function to be executed when the animation ends
  25752. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25753. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25754. * @returns the animatable object created for this animation
  25755. */
  25756. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25757. if (weight === void 0) { weight = 1.0; }
  25758. if (speedRatio === void 0) { speedRatio = 1.0; }
  25759. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25760. returnedAnimatable.weight = weight;
  25761. return returnedAnimatable;
  25762. };
  25763. /**
  25764. * Will start the animation sequence of a given target
  25765. * @param target defines the target
  25766. * @param from defines from which frame should animation start
  25767. * @param to defines until which frame should animation run.
  25768. * @param loop defines if the animation loops
  25769. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25770. * @param onAnimationEnd defines the function to be executed when the animation ends
  25771. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25772. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25773. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25774. * @returns the animatable object created for this animation
  25775. */
  25776. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25777. if (speedRatio === void 0) { speedRatio = 1.0; }
  25778. if (stopCurrent === void 0) { stopCurrent = true; }
  25779. if (from > to && speedRatio > 0) {
  25780. speedRatio *= -1;
  25781. }
  25782. if (stopCurrent) {
  25783. this.stopAnimation(target, undefined, targetMask);
  25784. }
  25785. if (!animatable) {
  25786. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25787. }
  25788. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25789. // Local animations
  25790. if (target.animations && shouldRunTargetAnimations) {
  25791. animatable.appendAnimations(target, target.animations);
  25792. }
  25793. // Children animations
  25794. if (target.getAnimatables) {
  25795. var animatables = target.getAnimatables();
  25796. for (var index = 0; index < animatables.length; index++) {
  25797. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25798. }
  25799. }
  25800. animatable.reset();
  25801. return animatable;
  25802. };
  25803. /**
  25804. * Begin a new animation on a given node
  25805. * @param target defines the target where the animation will take place
  25806. * @param animations defines the list of animations to start
  25807. * @param from defines the initial value
  25808. * @param to defines the final value
  25809. * @param loop defines if you want animation to loop (off by default)
  25810. * @param speedRatio defines the speed ratio to apply to all animations
  25811. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25812. * @returns the list of created animatables
  25813. */
  25814. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25815. if (speedRatio === undefined) {
  25816. speedRatio = 1.0;
  25817. }
  25818. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25819. return animatable;
  25820. };
  25821. /**
  25822. * Begin a new animation on a given node and its hierarchy
  25823. * @param target defines the root node where the animation will take place
  25824. * @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.
  25825. * @param animations defines the list of animations to start
  25826. * @param from defines the initial value
  25827. * @param to defines the final value
  25828. * @param loop defines if you want animation to loop (off by default)
  25829. * @param speedRatio defines the speed ratio to apply to all animations
  25830. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25831. * @returns the list of animatables created for all nodes
  25832. */
  25833. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25834. var children = target.getDescendants(directDescendantsOnly);
  25835. var result = [];
  25836. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25837. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25838. var child = children_1[_i];
  25839. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25840. }
  25841. return result;
  25842. };
  25843. /**
  25844. * Gets the animatable associated with a specific target
  25845. * @param target defines the target of the animatable
  25846. * @returns the required animatable if found
  25847. */
  25848. Scene.prototype.getAnimatableByTarget = function (target) {
  25849. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25850. if (this._activeAnimatables[index].target === target) {
  25851. return this._activeAnimatables[index];
  25852. }
  25853. }
  25854. return null;
  25855. };
  25856. /**
  25857. * Gets all animatables associated with a given target
  25858. * @param target defines the target to look animatables for
  25859. * @returns an array of Animatables
  25860. */
  25861. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25862. var result = [];
  25863. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25864. if (this._activeAnimatables[index].target === target) {
  25865. result.push(this._activeAnimatables[index]);
  25866. }
  25867. }
  25868. return result;
  25869. };
  25870. Object.defineProperty(Scene.prototype, "animatables", {
  25871. /**
  25872. * Gets all animatable attached to the scene
  25873. */
  25874. get: function () {
  25875. return this._activeAnimatables;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. /**
  25881. * Will stop the animation of the given target
  25882. * @param target - the target
  25883. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25884. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  25885. */
  25886. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25887. var animatables = this.getAllAnimatablesByTarget(target);
  25888. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25889. var animatable = animatables_1[_i];
  25890. animatable.stop(animationName, targetMask);
  25891. }
  25892. };
  25893. /**
  25894. * Stops and removes all animations that have been applied to the scene
  25895. */
  25896. Scene.prototype.stopAllAnimations = function () {
  25897. if (this._activeAnimatables) {
  25898. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25899. this._activeAnimatables[i].stop();
  25900. }
  25901. this._activeAnimatables = [];
  25902. }
  25903. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25904. var group = _a[_i];
  25905. group.stop();
  25906. }
  25907. };
  25908. Scene.prototype._animate = function () {
  25909. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25910. return;
  25911. }
  25912. // Getting time
  25913. var now = BABYLON.Tools.Now;
  25914. if (!this._animationTimeLast) {
  25915. if (this._pendingData.length > 0) {
  25916. return;
  25917. }
  25918. this._animationTimeLast = now;
  25919. }
  25920. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25921. this._animationTime += deltaTime;
  25922. this._animationTimeLast = now;
  25923. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25924. this._activeAnimatables[index]._animate(this._animationTime);
  25925. }
  25926. // Late animation bindings
  25927. this._processLateAnimationBindings();
  25928. };
  25929. /** @hidden */
  25930. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25931. var target = runtimeAnimation.target;
  25932. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25933. if (!target._lateAnimationHolders) {
  25934. target._lateAnimationHolders = {};
  25935. }
  25936. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25937. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25938. totalWeight: 0,
  25939. animations: [],
  25940. originalValue: originalValue
  25941. };
  25942. }
  25943. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25944. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25945. };
  25946. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25947. var normalizer = 1.0;
  25948. var finalPosition = BABYLON.Tmp.Vector3[0];
  25949. var finalScaling = BABYLON.Tmp.Vector3[1];
  25950. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25951. var startIndex = 0;
  25952. var originalAnimation = holder.animations[0];
  25953. var originalValue = holder.originalValue;
  25954. var scale = 1;
  25955. if (holder.totalWeight < 1.0) {
  25956. // We need to mix the original value in
  25957. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25958. scale = 1.0 - holder.totalWeight;
  25959. }
  25960. else {
  25961. startIndex = 1;
  25962. // We need to normalize the weights
  25963. normalizer = holder.totalWeight;
  25964. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25965. scale = originalAnimation.weight / normalizer;
  25966. if (scale == 1) {
  25967. return originalAnimation.currentValue;
  25968. }
  25969. }
  25970. finalScaling.scaleInPlace(scale);
  25971. finalPosition.scaleInPlace(scale);
  25972. finalQuaternion.scaleInPlace(scale);
  25973. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25974. var runtimeAnimation = holder.animations[animIndex];
  25975. var scale = runtimeAnimation.weight / normalizer;
  25976. var currentPosition = BABYLON.Tmp.Vector3[2];
  25977. var currentScaling = BABYLON.Tmp.Vector3[3];
  25978. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25979. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25980. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25981. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25982. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25983. }
  25984. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25985. return originalAnimation._workValue;
  25986. };
  25987. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25988. var originalAnimation = holder.animations[0];
  25989. var originalValue = holder.originalValue;
  25990. if (holder.animations.length === 1) {
  25991. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25992. }
  25993. var normalizer = 1.0;
  25994. var quaternions;
  25995. var weights;
  25996. if (holder.totalWeight < 1.0) {
  25997. var scale = 1.0 - holder.totalWeight;
  25998. quaternions = [];
  25999. weights = [];
  26000. quaternions.push(originalValue);
  26001. weights.push(scale);
  26002. }
  26003. else {
  26004. if (holder.animations.length === 2) { // Slerp as soon as we can
  26005. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26006. }
  26007. quaternions = [];
  26008. weights = [];
  26009. normalizer = holder.totalWeight;
  26010. }
  26011. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26012. var runtimeAnimation = holder.animations[animIndex];
  26013. quaternions.push(runtimeAnimation.currentValue);
  26014. weights.push(runtimeAnimation.weight / normalizer);
  26015. }
  26016. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26017. var cumulativeAmount = 0;
  26018. var cumulativeQuaternion = null;
  26019. for (var index = 0; index < quaternions.length;) {
  26020. if (!cumulativeQuaternion) {
  26021. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26022. cumulativeAmount = weights[index] + weights[index + 1];
  26023. index += 2;
  26024. continue;
  26025. }
  26026. cumulativeAmount += weights[index];
  26027. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26028. index++;
  26029. }
  26030. return cumulativeQuaternion;
  26031. };
  26032. Scene.prototype._processLateAnimationBindings = function () {
  26033. if (!this._registeredForLateAnimationBindings.length) {
  26034. return;
  26035. }
  26036. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26037. var target = this._registeredForLateAnimationBindings.data[index];
  26038. for (var path in target._lateAnimationHolders) {
  26039. var holder = target._lateAnimationHolders[path];
  26040. var originalAnimation = holder.animations[0];
  26041. var originalValue = holder.originalValue;
  26042. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26043. var finalValue = void 0;
  26044. if (matrixDecomposeMode) {
  26045. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26046. }
  26047. else {
  26048. var quaternionMode = originalValue.w !== undefined;
  26049. if (quaternionMode) {
  26050. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26051. }
  26052. else {
  26053. var startIndex = 0;
  26054. var normalizer = 1.0;
  26055. if (holder.totalWeight < 1.0) {
  26056. // We need to mix the original value in
  26057. if (originalValue.scale) {
  26058. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26059. }
  26060. else {
  26061. finalValue = originalValue * (1.0 - holder.totalWeight);
  26062. }
  26063. }
  26064. else {
  26065. // We need to normalize the weights
  26066. normalizer = holder.totalWeight;
  26067. var scale_1 = originalAnimation.weight / normalizer;
  26068. if (scale_1 !== 1) {
  26069. if (originalAnimation.currentValue.scale) {
  26070. finalValue = originalAnimation.currentValue.scale(scale_1);
  26071. }
  26072. else {
  26073. finalValue = originalAnimation.currentValue * scale_1;
  26074. }
  26075. }
  26076. else {
  26077. finalValue = originalAnimation.currentValue;
  26078. }
  26079. startIndex = 1;
  26080. }
  26081. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26082. var runtimeAnimation = holder.animations[animIndex];
  26083. var scale = runtimeAnimation.weight / normalizer;
  26084. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26085. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26086. }
  26087. else {
  26088. finalValue += runtimeAnimation.currentValue * scale;
  26089. }
  26090. }
  26091. }
  26092. }
  26093. target[path] = finalValue;
  26094. }
  26095. target._lateAnimationHolders = {};
  26096. }
  26097. this._registeredForLateAnimationBindings.reset();
  26098. };
  26099. // Matrix
  26100. /** @hidden */
  26101. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26102. this._useAlternateCameraConfiguration = active;
  26103. };
  26104. /**
  26105. * Gets the current view matrix
  26106. * @returns a Matrix
  26107. */
  26108. Scene.prototype.getViewMatrix = function () {
  26109. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26110. };
  26111. /**
  26112. * Gets the current projection matrix
  26113. * @returns a Matrix
  26114. */
  26115. Scene.prototype.getProjectionMatrix = function () {
  26116. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26117. };
  26118. /**
  26119. * Gets the current transform matrix
  26120. * @returns a Matrix made of View * Projection
  26121. */
  26122. Scene.prototype.getTransformMatrix = function () {
  26123. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26124. };
  26125. /**
  26126. * Sets the current transform matrix
  26127. * @param view defines the View matrix to use
  26128. * @param projection defines the Projection matrix to use
  26129. */
  26130. Scene.prototype.setTransformMatrix = function (view, projection) {
  26131. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26132. return;
  26133. }
  26134. this._viewUpdateFlag = view.updateFlag;
  26135. this._projectionUpdateFlag = projection.updateFlag;
  26136. this._viewMatrix = view;
  26137. this._projectionMatrix = projection;
  26138. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26139. // Update frustum
  26140. if (!this._frustumPlanes) {
  26141. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26142. }
  26143. else {
  26144. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26145. }
  26146. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26147. var otherCamera = this.activeCamera._alternateCamera;
  26148. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26149. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26150. }
  26151. if (this._sceneUbo.useUbo) {
  26152. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26153. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26154. this._sceneUbo.update();
  26155. }
  26156. };
  26157. /** @hidden */
  26158. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26159. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26160. return;
  26161. }
  26162. this._alternateViewUpdateFlag = view.updateFlag;
  26163. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26164. this._alternateViewMatrix = view;
  26165. this._alternateProjectionMatrix = projection;
  26166. if (!this._alternateTransformMatrix) {
  26167. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26168. }
  26169. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26170. if (!this._alternateSceneUbo) {
  26171. this._createAlternateUbo();
  26172. }
  26173. if (this._alternateSceneUbo.useUbo) {
  26174. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26175. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26176. this._alternateSceneUbo.update();
  26177. }
  26178. };
  26179. /**
  26180. * Gets the uniform buffer used to store scene data
  26181. * @returns a UniformBuffer
  26182. */
  26183. Scene.prototype.getSceneUniformBuffer = function () {
  26184. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26185. };
  26186. /**
  26187. * Gets an unique (relatively to the current scene) Id
  26188. * @returns an unique number for the scene
  26189. */
  26190. Scene.prototype.getUniqueId = function () {
  26191. var result = Scene._uniqueIdCounter;
  26192. Scene._uniqueIdCounter++;
  26193. return result;
  26194. };
  26195. /**
  26196. * Add a mesh to the list of scene's meshes
  26197. * @param newMesh defines the mesh to add
  26198. * @param recursive if all child meshes should also be added to the scene
  26199. */
  26200. Scene.prototype.addMesh = function (newMesh, recursive) {
  26201. var _this = this;
  26202. if (recursive === void 0) { recursive = false; }
  26203. this.meshes.push(newMesh);
  26204. //notify the collision coordinator
  26205. if (this.collisionCoordinator) {
  26206. this.collisionCoordinator.onMeshAdded(newMesh);
  26207. }
  26208. newMesh._resyncLightSources();
  26209. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26210. if (recursive) {
  26211. newMesh.getChildMeshes().forEach(function (m) {
  26212. _this.addMesh(m);
  26213. });
  26214. }
  26215. };
  26216. /**
  26217. * Remove a mesh for the list of scene's meshes
  26218. * @param toRemove defines the mesh to remove
  26219. * @param recursive if all child meshes should also be removed from the scene
  26220. * @returns the index where the mesh was in the mesh list
  26221. */
  26222. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26223. var _this = this;
  26224. if (recursive === void 0) { recursive = false; }
  26225. var index = this.meshes.indexOf(toRemove);
  26226. if (index !== -1) {
  26227. // Remove from the scene if mesh found
  26228. this.meshes.splice(index, 1);
  26229. }
  26230. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26231. if (recursive) {
  26232. toRemove.getChildMeshes().forEach(function (m) {
  26233. _this.removeMesh(m);
  26234. });
  26235. }
  26236. return index;
  26237. };
  26238. /**
  26239. * Add a transform node to the list of scene's transform nodes
  26240. * @param newTransformNode defines the transform node to add
  26241. */
  26242. Scene.prototype.addTransformNode = function (newTransformNode) {
  26243. this.transformNodes.push(newTransformNode);
  26244. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26245. };
  26246. /**
  26247. * Remove a transform node for the list of scene's transform nodes
  26248. * @param toRemove defines the transform node to remove
  26249. * @returns the index where the transform node was in the transform node list
  26250. */
  26251. Scene.prototype.removeTransformNode = function (toRemove) {
  26252. var index = this.transformNodes.indexOf(toRemove);
  26253. if (index !== -1) {
  26254. // Remove from the scene if found
  26255. this.transformNodes.splice(index, 1);
  26256. }
  26257. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26258. return index;
  26259. };
  26260. /**
  26261. * Remove a skeleton for the list of scene's skeletons
  26262. * @param toRemove defines the skeleton to remove
  26263. * @returns the index where the skeleton was in the skeleton list
  26264. */
  26265. Scene.prototype.removeSkeleton = function (toRemove) {
  26266. var index = this.skeletons.indexOf(toRemove);
  26267. if (index !== -1) {
  26268. // Remove from the scene if found
  26269. this.skeletons.splice(index, 1);
  26270. }
  26271. return index;
  26272. };
  26273. /**
  26274. * Remove a morph target for the list of scene's morph targets
  26275. * @param toRemove defines the morph target to remove
  26276. * @returns the index where the morph target was in the morph target list
  26277. */
  26278. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26279. var index = this.morphTargetManagers.indexOf(toRemove);
  26280. if (index !== -1) {
  26281. // Remove from the scene if found
  26282. this.morphTargetManagers.splice(index, 1);
  26283. }
  26284. return index;
  26285. };
  26286. /**
  26287. * Remove a light for the list of scene's lights
  26288. * @param toRemove defines the light to remove
  26289. * @returns the index where the light was in the light list
  26290. */
  26291. Scene.prototype.removeLight = function (toRemove) {
  26292. var index = this.lights.indexOf(toRemove);
  26293. if (index !== -1) {
  26294. // Remove from meshes
  26295. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26296. var mesh = _a[_i];
  26297. mesh._removeLightSource(toRemove);
  26298. }
  26299. // Remove from the scene if mesh found
  26300. this.lights.splice(index, 1);
  26301. this.sortLightsByPriority();
  26302. }
  26303. this.onLightRemovedObservable.notifyObservers(toRemove);
  26304. return index;
  26305. };
  26306. /**
  26307. * Remove a camera for the list of scene's cameras
  26308. * @param toRemove defines the camera to remove
  26309. * @returns the index where the camera was in the camera list
  26310. */
  26311. Scene.prototype.removeCamera = function (toRemove) {
  26312. var index = this.cameras.indexOf(toRemove);
  26313. if (index !== -1) {
  26314. // Remove from the scene if mesh found
  26315. this.cameras.splice(index, 1);
  26316. }
  26317. // Remove from activeCameras
  26318. var index2 = this.activeCameras.indexOf(toRemove);
  26319. if (index2 !== -1) {
  26320. // Remove from the scene if mesh found
  26321. this.activeCameras.splice(index2, 1);
  26322. }
  26323. // Reset the activeCamera
  26324. if (this.activeCamera === toRemove) {
  26325. if (this.cameras.length > 0) {
  26326. this.activeCamera = this.cameras[0];
  26327. }
  26328. else {
  26329. this.activeCamera = null;
  26330. }
  26331. }
  26332. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26333. return index;
  26334. };
  26335. /**
  26336. * Remove a particle system for the list of scene's particle systems
  26337. * @param toRemove defines the particle system to remove
  26338. * @returns the index where the particle system was in the particle system list
  26339. */
  26340. Scene.prototype.removeParticleSystem = function (toRemove) {
  26341. var index = this.particleSystems.indexOf(toRemove);
  26342. if (index !== -1) {
  26343. this.particleSystems.splice(index, 1);
  26344. }
  26345. return index;
  26346. };
  26347. /**
  26348. * Remove a animation for the list of scene's animations
  26349. * @param toRemove defines the animation to remove
  26350. * @returns the index where the animation was in the animation list
  26351. */
  26352. Scene.prototype.removeAnimation = function (toRemove) {
  26353. var index = this.animations.indexOf(toRemove);
  26354. if (index !== -1) {
  26355. this.animations.splice(index, 1);
  26356. }
  26357. return index;
  26358. };
  26359. /**
  26360. * Removes the given animation group from this scene.
  26361. * @param toRemove The animation group to remove
  26362. * @returns The index of the removed animation group
  26363. */
  26364. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26365. var index = this.animationGroups.indexOf(toRemove);
  26366. if (index !== -1) {
  26367. this.animationGroups.splice(index, 1);
  26368. }
  26369. return index;
  26370. };
  26371. /**
  26372. * Removes the given multi-material from this scene.
  26373. * @param toRemove The multi-material to remove
  26374. * @returns The index of the removed multi-material
  26375. */
  26376. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26377. var index = this.multiMaterials.indexOf(toRemove);
  26378. if (index !== -1) {
  26379. this.multiMaterials.splice(index, 1);
  26380. }
  26381. return index;
  26382. };
  26383. /**
  26384. * Removes the given material from this scene.
  26385. * @param toRemove The material to remove
  26386. * @returns The index of the removed material
  26387. */
  26388. Scene.prototype.removeMaterial = function (toRemove) {
  26389. var index = this.materials.indexOf(toRemove);
  26390. if (index !== -1) {
  26391. this.materials.splice(index, 1);
  26392. }
  26393. return index;
  26394. };
  26395. /**
  26396. * Removes the given action manager from this scene.
  26397. * @param toRemove The action manager to remove
  26398. * @returns The index of the removed action manager
  26399. */
  26400. Scene.prototype.removeActionManager = function (toRemove) {
  26401. var index = this.actionManagers.indexOf(toRemove);
  26402. if (index !== -1) {
  26403. this.actionManagers.splice(index, 1);
  26404. }
  26405. return index;
  26406. };
  26407. /**
  26408. * Removes the given texture from this scene.
  26409. * @param toRemove The texture to remove
  26410. * @returns The index of the removed texture
  26411. */
  26412. Scene.prototype.removeTexture = function (toRemove) {
  26413. var index = this.textures.indexOf(toRemove);
  26414. if (index !== -1) {
  26415. this.textures.splice(index, 1);
  26416. }
  26417. return index;
  26418. };
  26419. /**
  26420. * Adds the given light to this scene
  26421. * @param newLight The light to add
  26422. */
  26423. Scene.prototype.addLight = function (newLight) {
  26424. this.lights.push(newLight);
  26425. this.sortLightsByPriority();
  26426. // Add light to all meshes (To support if the light is removed and then readded)
  26427. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26428. var mesh = _a[_i];
  26429. if (mesh._lightSources.indexOf(newLight) === -1) {
  26430. mesh._lightSources.push(newLight);
  26431. mesh._resyncLightSources();
  26432. }
  26433. }
  26434. this.onNewLightAddedObservable.notifyObservers(newLight);
  26435. };
  26436. /**
  26437. * Sorts the list list based on light priorities
  26438. */
  26439. Scene.prototype.sortLightsByPriority = function () {
  26440. if (this.requireLightSorting) {
  26441. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26442. }
  26443. };
  26444. /**
  26445. * Adds the given camera to this scene
  26446. * @param newCamera The camera to add
  26447. */
  26448. Scene.prototype.addCamera = function (newCamera) {
  26449. this.cameras.push(newCamera);
  26450. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26451. };
  26452. /**
  26453. * Adds the given skeleton to this scene
  26454. * @param newSkeleton The skeleton to add
  26455. */
  26456. Scene.prototype.addSkeleton = function (newSkeleton) {
  26457. this.skeletons.push(newSkeleton);
  26458. };
  26459. /**
  26460. * Adds the given particle system to this scene
  26461. * @param newParticleSystem The particle system to add
  26462. */
  26463. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26464. this.particleSystems.push(newParticleSystem);
  26465. };
  26466. /**
  26467. * Adds the given animation to this scene
  26468. * @param newAnimation The animation to add
  26469. */
  26470. Scene.prototype.addAnimation = function (newAnimation) {
  26471. this.animations.push(newAnimation);
  26472. };
  26473. /**
  26474. * Adds the given animation group to this scene.
  26475. * @param newAnimationGroup The animation group to add
  26476. */
  26477. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26478. this.animationGroups.push(newAnimationGroup);
  26479. };
  26480. /**
  26481. * Adds the given multi-material to this scene
  26482. * @param newMultiMaterial The multi-material to add
  26483. */
  26484. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26485. this.multiMaterials.push(newMultiMaterial);
  26486. };
  26487. /**
  26488. * Adds the given material to this scene
  26489. * @param newMaterial The material to add
  26490. */
  26491. Scene.prototype.addMaterial = function (newMaterial) {
  26492. this.materials.push(newMaterial);
  26493. };
  26494. /**
  26495. * Adds the given morph target to this scene
  26496. * @param newMorphTargetManager The morph target to add
  26497. */
  26498. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26499. this.morphTargetManagers.push(newMorphTargetManager);
  26500. };
  26501. /**
  26502. * Adds the given geometry to this scene
  26503. * @param newGeometry The geometry to add
  26504. */
  26505. Scene.prototype.addGeometry = function (newGeometry) {
  26506. this.geometries.push(newGeometry);
  26507. };
  26508. /**
  26509. * Adds the given action manager to this scene
  26510. * @param newActionManager The action manager to add
  26511. */
  26512. Scene.prototype.addActionManager = function (newActionManager) {
  26513. this.actionManagers.push(newActionManager);
  26514. };
  26515. /**
  26516. * Adds the given texture to this scene.
  26517. * @param newTexture The texture to add
  26518. */
  26519. Scene.prototype.addTexture = function (newTexture) {
  26520. this.textures.push(newTexture);
  26521. };
  26522. /**
  26523. * Switch active camera
  26524. * @param newCamera defines the new active camera
  26525. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26526. */
  26527. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26528. if (attachControl === void 0) { attachControl = true; }
  26529. var canvas = this._engine.getRenderingCanvas();
  26530. if (!canvas) {
  26531. return;
  26532. }
  26533. if (this.activeCamera) {
  26534. this.activeCamera.detachControl(canvas);
  26535. }
  26536. this.activeCamera = newCamera;
  26537. if (attachControl) {
  26538. newCamera.attachControl(canvas);
  26539. }
  26540. };
  26541. /**
  26542. * sets the active camera of the scene using its ID
  26543. * @param id defines the camera's ID
  26544. * @return the new active camera or null if none found.
  26545. */
  26546. Scene.prototype.setActiveCameraByID = function (id) {
  26547. var camera = this.getCameraByID(id);
  26548. if (camera) {
  26549. this.activeCamera = camera;
  26550. return camera;
  26551. }
  26552. return null;
  26553. };
  26554. /**
  26555. * sets the active camera of the scene using its name
  26556. * @param name defines the camera's name
  26557. * @returns the new active camera or null if none found.
  26558. */
  26559. Scene.prototype.setActiveCameraByName = function (name) {
  26560. var camera = this.getCameraByName(name);
  26561. if (camera) {
  26562. this.activeCamera = camera;
  26563. return camera;
  26564. }
  26565. return null;
  26566. };
  26567. /**
  26568. * get an animation group using its name
  26569. * @param name defines the material's name
  26570. * @return the animation group or null if none found.
  26571. */
  26572. Scene.prototype.getAnimationGroupByName = function (name) {
  26573. for (var index = 0; index < this.animationGroups.length; index++) {
  26574. if (this.animationGroups[index].name === name) {
  26575. return this.animationGroups[index];
  26576. }
  26577. }
  26578. return null;
  26579. };
  26580. /**
  26581. * get a material using its id
  26582. * @param id defines the material's ID
  26583. * @return the material or null if none found.
  26584. */
  26585. Scene.prototype.getMaterialByID = function (id) {
  26586. for (var index = 0; index < this.materials.length; index++) {
  26587. if (this.materials[index].id === id) {
  26588. return this.materials[index];
  26589. }
  26590. }
  26591. return null;
  26592. };
  26593. /**
  26594. * Gets a material using its name
  26595. * @param name defines the material's name
  26596. * @return the material or null if none found.
  26597. */
  26598. Scene.prototype.getMaterialByName = function (name) {
  26599. for (var index = 0; index < this.materials.length; index++) {
  26600. if (this.materials[index].name === name) {
  26601. return this.materials[index];
  26602. }
  26603. }
  26604. return null;
  26605. };
  26606. /**
  26607. * Gets a camera using its id
  26608. * @param id defines the id to look for
  26609. * @returns the camera or null if not found
  26610. */
  26611. Scene.prototype.getCameraByID = function (id) {
  26612. for (var index = 0; index < this.cameras.length; index++) {
  26613. if (this.cameras[index].id === id) {
  26614. return this.cameras[index];
  26615. }
  26616. }
  26617. return null;
  26618. };
  26619. /**
  26620. * Gets a camera using its unique id
  26621. * @param uniqueId defines the unique id to look for
  26622. * @returns the camera or null if not found
  26623. */
  26624. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26625. for (var index = 0; index < this.cameras.length; index++) {
  26626. if (this.cameras[index].uniqueId === uniqueId) {
  26627. return this.cameras[index];
  26628. }
  26629. }
  26630. return null;
  26631. };
  26632. /**
  26633. * Gets a camera using its name
  26634. * @param name defines the camera's name
  26635. * @return the camera or null if none found.
  26636. */
  26637. Scene.prototype.getCameraByName = function (name) {
  26638. for (var index = 0; index < this.cameras.length; index++) {
  26639. if (this.cameras[index].name === name) {
  26640. return this.cameras[index];
  26641. }
  26642. }
  26643. return null;
  26644. };
  26645. /**
  26646. * Gets a bone using its id
  26647. * @param id defines the bone's id
  26648. * @return the bone or null if not found
  26649. */
  26650. Scene.prototype.getBoneByID = function (id) {
  26651. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26652. var skeleton = this.skeletons[skeletonIndex];
  26653. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26654. if (skeleton.bones[boneIndex].id === id) {
  26655. return skeleton.bones[boneIndex];
  26656. }
  26657. }
  26658. }
  26659. return null;
  26660. };
  26661. /**
  26662. * Gets a bone using its id
  26663. * @param name defines the bone's name
  26664. * @return the bone or null if not found
  26665. */
  26666. Scene.prototype.getBoneByName = function (name) {
  26667. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26668. var skeleton = this.skeletons[skeletonIndex];
  26669. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26670. if (skeleton.bones[boneIndex].name === name) {
  26671. return skeleton.bones[boneIndex];
  26672. }
  26673. }
  26674. }
  26675. return null;
  26676. };
  26677. /**
  26678. * Gets a light node using its name
  26679. * @param name defines the the light's name
  26680. * @return the light or null if none found.
  26681. */
  26682. Scene.prototype.getLightByName = function (name) {
  26683. for (var index = 0; index < this.lights.length; index++) {
  26684. if (this.lights[index].name === name) {
  26685. return this.lights[index];
  26686. }
  26687. }
  26688. return null;
  26689. };
  26690. /**
  26691. * Gets a light node using its id
  26692. * @param id defines the light's id
  26693. * @return the light or null if none found.
  26694. */
  26695. Scene.prototype.getLightByID = function (id) {
  26696. for (var index = 0; index < this.lights.length; index++) {
  26697. if (this.lights[index].id === id) {
  26698. return this.lights[index];
  26699. }
  26700. }
  26701. return null;
  26702. };
  26703. /**
  26704. * Gets a light node using its scene-generated unique ID
  26705. * @param uniqueId defines the light's unique id
  26706. * @return the light or null if none found.
  26707. */
  26708. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26709. for (var index = 0; index < this.lights.length; index++) {
  26710. if (this.lights[index].uniqueId === uniqueId) {
  26711. return this.lights[index];
  26712. }
  26713. }
  26714. return null;
  26715. };
  26716. /**
  26717. * Gets a particle system by id
  26718. * @param id defines the particle system id
  26719. * @return the corresponding system or null if none found
  26720. */
  26721. Scene.prototype.getParticleSystemByID = function (id) {
  26722. for (var index = 0; index < this.particleSystems.length; index++) {
  26723. if (this.particleSystems[index].id === id) {
  26724. return this.particleSystems[index];
  26725. }
  26726. }
  26727. return null;
  26728. };
  26729. /**
  26730. * Gets a geometry using its ID
  26731. * @param id defines the geometry's id
  26732. * @return the geometry or null if none found.
  26733. */
  26734. Scene.prototype.getGeometryByID = function (id) {
  26735. for (var index = 0; index < this.geometries.length; index++) {
  26736. if (this.geometries[index].id === id) {
  26737. return this.geometries[index];
  26738. }
  26739. }
  26740. return null;
  26741. };
  26742. /**
  26743. * Add a new geometry to this scene
  26744. * @param geometry defines the geometry to be added to the scene.
  26745. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26746. * @return a boolean defining if the geometry was added or not
  26747. */
  26748. Scene.prototype.pushGeometry = function (geometry, force) {
  26749. if (!force && this.getGeometryByID(geometry.id)) {
  26750. return false;
  26751. }
  26752. this.geometries.push(geometry);
  26753. //notify the collision coordinator
  26754. if (this.collisionCoordinator) {
  26755. this.collisionCoordinator.onGeometryAdded(geometry);
  26756. }
  26757. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26758. return true;
  26759. };
  26760. /**
  26761. * Removes an existing geometry
  26762. * @param geometry defines the geometry to be removed from the scene
  26763. * @return a boolean defining if the geometry was removed or not
  26764. */
  26765. Scene.prototype.removeGeometry = function (geometry) {
  26766. var index = this.geometries.indexOf(geometry);
  26767. if (index > -1) {
  26768. this.geometries.splice(index, 1);
  26769. //notify the collision coordinator
  26770. if (this.collisionCoordinator) {
  26771. this.collisionCoordinator.onGeometryDeleted(geometry);
  26772. }
  26773. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26774. return true;
  26775. }
  26776. return false;
  26777. };
  26778. /**
  26779. * Gets the list of geometries attached to the scene
  26780. * @returns an array of Geometry
  26781. */
  26782. Scene.prototype.getGeometries = function () {
  26783. return this.geometries;
  26784. };
  26785. /**
  26786. * Gets the first added mesh found of a given ID
  26787. * @param id defines the id to search for
  26788. * @return the mesh found or null if not found at all
  26789. */
  26790. Scene.prototype.getMeshByID = function (id) {
  26791. for (var index = 0; index < this.meshes.length; index++) {
  26792. if (this.meshes[index].id === id) {
  26793. return this.meshes[index];
  26794. }
  26795. }
  26796. return null;
  26797. };
  26798. /**
  26799. * Gets a list of meshes using their id
  26800. * @param id defines the id to search for
  26801. * @returns a list of meshes
  26802. */
  26803. Scene.prototype.getMeshesByID = function (id) {
  26804. return this.meshes.filter(function (m) {
  26805. return m.id === id;
  26806. });
  26807. };
  26808. /**
  26809. * Gets the first added transform node found of a given ID
  26810. * @param id defines the id to search for
  26811. * @return the found transform node or null if not found at all.
  26812. */
  26813. Scene.prototype.getTransformNodeByID = function (id) {
  26814. for (var index = 0; index < this.transformNodes.length; index++) {
  26815. if (this.transformNodes[index].id === id) {
  26816. return this.transformNodes[index];
  26817. }
  26818. }
  26819. return null;
  26820. };
  26821. /**
  26822. * Gets a list of transform nodes using their id
  26823. * @param id defines the id to search for
  26824. * @returns a list of transform nodes
  26825. */
  26826. Scene.prototype.getTransformNodesByID = function (id) {
  26827. return this.transformNodes.filter(function (m) {
  26828. return m.id === id;
  26829. });
  26830. };
  26831. /**
  26832. * Gets a mesh with its auto-generated unique id
  26833. * @param uniqueId defines the unique id to search for
  26834. * @return the found mesh or null if not found at all.
  26835. */
  26836. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26837. for (var index = 0; index < this.meshes.length; index++) {
  26838. if (this.meshes[index].uniqueId === uniqueId) {
  26839. return this.meshes[index];
  26840. }
  26841. }
  26842. return null;
  26843. };
  26844. /**
  26845. * Gets a the last added mesh using a given id
  26846. * @param id defines the id to search for
  26847. * @return the found mesh or null if not found at all.
  26848. */
  26849. Scene.prototype.getLastMeshByID = function (id) {
  26850. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26851. if (this.meshes[index].id === id) {
  26852. return this.meshes[index];
  26853. }
  26854. }
  26855. return null;
  26856. };
  26857. /**
  26858. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26859. * @param id defines the id to search for
  26860. * @return the found node or null if not found at all
  26861. */
  26862. Scene.prototype.getLastEntryByID = function (id) {
  26863. var index;
  26864. for (index = this.meshes.length - 1; index >= 0; index--) {
  26865. if (this.meshes[index].id === id) {
  26866. return this.meshes[index];
  26867. }
  26868. }
  26869. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26870. if (this.transformNodes[index].id === id) {
  26871. return this.transformNodes[index];
  26872. }
  26873. }
  26874. for (index = this.cameras.length - 1; index >= 0; index--) {
  26875. if (this.cameras[index].id === id) {
  26876. return this.cameras[index];
  26877. }
  26878. }
  26879. for (index = this.lights.length - 1; index >= 0; index--) {
  26880. if (this.lights[index].id === id) {
  26881. return this.lights[index];
  26882. }
  26883. }
  26884. return null;
  26885. };
  26886. /**
  26887. * Gets a node (Mesh, Camera, Light) using a given id
  26888. * @param id defines the id to search for
  26889. * @return the found node or null if not found at all
  26890. */
  26891. Scene.prototype.getNodeByID = function (id) {
  26892. var mesh = this.getMeshByID(id);
  26893. if (mesh) {
  26894. return mesh;
  26895. }
  26896. var light = this.getLightByID(id);
  26897. if (light) {
  26898. return light;
  26899. }
  26900. var camera = this.getCameraByID(id);
  26901. if (camera) {
  26902. return camera;
  26903. }
  26904. var bone = this.getBoneByID(id);
  26905. return bone;
  26906. };
  26907. /**
  26908. * Gets a node (Mesh, Camera, Light) using a given name
  26909. * @param name defines the name to search for
  26910. * @return the found node or null if not found at all.
  26911. */
  26912. Scene.prototype.getNodeByName = function (name) {
  26913. var mesh = this.getMeshByName(name);
  26914. if (mesh) {
  26915. return mesh;
  26916. }
  26917. var light = this.getLightByName(name);
  26918. if (light) {
  26919. return light;
  26920. }
  26921. var camera = this.getCameraByName(name);
  26922. if (camera) {
  26923. return camera;
  26924. }
  26925. var bone = this.getBoneByName(name);
  26926. return bone;
  26927. };
  26928. /**
  26929. * Gets a mesh using a given name
  26930. * @param name defines the name to search for
  26931. * @return the found mesh or null if not found at all.
  26932. */
  26933. Scene.prototype.getMeshByName = function (name) {
  26934. for (var index = 0; index < this.meshes.length; index++) {
  26935. if (this.meshes[index].name === name) {
  26936. return this.meshes[index];
  26937. }
  26938. }
  26939. return null;
  26940. };
  26941. /**
  26942. * Gets a transform node using a given name
  26943. * @param name defines the name to search for
  26944. * @return the found transform node or null if not found at all.
  26945. */
  26946. Scene.prototype.getTransformNodeByName = function (name) {
  26947. for (var index = 0; index < this.transformNodes.length; index++) {
  26948. if (this.transformNodes[index].name === name) {
  26949. return this.transformNodes[index];
  26950. }
  26951. }
  26952. return null;
  26953. };
  26954. /**
  26955. * Gets a sound using a given name
  26956. * @param name defines the name to search for
  26957. * @return the found sound or null if not found at all.
  26958. */
  26959. Scene.prototype.getSoundByName = function (name) {
  26960. var index;
  26961. if (BABYLON.AudioEngine) {
  26962. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26963. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26964. return this.mainSoundTrack.soundCollection[index];
  26965. }
  26966. }
  26967. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26968. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26969. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26970. return this.soundTracks[sdIndex].soundCollection[index];
  26971. }
  26972. }
  26973. }
  26974. }
  26975. return null;
  26976. };
  26977. /**
  26978. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26979. * @param id defines the id to search for
  26980. * @return the found skeleton or null if not found at all.
  26981. */
  26982. Scene.prototype.getLastSkeletonByID = function (id) {
  26983. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26984. if (this.skeletons[index].id === id) {
  26985. return this.skeletons[index];
  26986. }
  26987. }
  26988. return null;
  26989. };
  26990. /**
  26991. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26992. * @param id defines the id to search for
  26993. * @return the found skeleton or null if not found at all.
  26994. */
  26995. Scene.prototype.getSkeletonById = function (id) {
  26996. for (var index = 0; index < this.skeletons.length; index++) {
  26997. if (this.skeletons[index].id === id) {
  26998. return this.skeletons[index];
  26999. }
  27000. }
  27001. return null;
  27002. };
  27003. /**
  27004. * Gets a skeleton using a given name
  27005. * @param name defines the name to search for
  27006. * @return the found skeleton or null if not found at all.
  27007. */
  27008. Scene.prototype.getSkeletonByName = function (name) {
  27009. for (var index = 0; index < this.skeletons.length; index++) {
  27010. if (this.skeletons[index].name === name) {
  27011. return this.skeletons[index];
  27012. }
  27013. }
  27014. return null;
  27015. };
  27016. /**
  27017. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27018. * @param id defines the id to search for
  27019. * @return the found morph target manager or null if not found at all.
  27020. */
  27021. Scene.prototype.getMorphTargetManagerById = function (id) {
  27022. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27023. if (this.morphTargetManagers[index].uniqueId === id) {
  27024. return this.morphTargetManagers[index];
  27025. }
  27026. }
  27027. return null;
  27028. };
  27029. /**
  27030. * Gets a boolean indicating if the given mesh is active
  27031. * @param mesh defines the mesh to look for
  27032. * @returns true if the mesh is in the active list
  27033. */
  27034. Scene.prototype.isActiveMesh = function (mesh) {
  27035. return (this._activeMeshes.indexOf(mesh) !== -1);
  27036. };
  27037. Object.defineProperty(Scene.prototype, "uid", {
  27038. /**
  27039. * Return a unique id as a string which can serve as an identifier for the scene
  27040. */
  27041. get: function () {
  27042. if (!this._uid) {
  27043. this._uid = BABYLON.Tools.RandomId();
  27044. }
  27045. return this._uid;
  27046. },
  27047. enumerable: true,
  27048. configurable: true
  27049. });
  27050. /**
  27051. * Add an externaly attached data from its key.
  27052. * This method call will fail and return false, if such key already exists.
  27053. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27054. * @param key the unique key that identifies the data
  27055. * @param data the data object to associate to the key for this Engine instance
  27056. * @return true if no such key were already present and the data was added successfully, false otherwise
  27057. */
  27058. Scene.prototype.addExternalData = function (key, data) {
  27059. if (!this._externalData) {
  27060. this._externalData = new BABYLON.StringDictionary();
  27061. }
  27062. return this._externalData.add(key, data);
  27063. };
  27064. /**
  27065. * Get an externaly attached data from its key
  27066. * @param key the unique key that identifies the data
  27067. * @return the associated data, if present (can be null), or undefined if not present
  27068. */
  27069. Scene.prototype.getExternalData = function (key) {
  27070. if (!this._externalData) {
  27071. return null;
  27072. }
  27073. return this._externalData.get(key);
  27074. };
  27075. /**
  27076. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27077. * @param key the unique key that identifies the data
  27078. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27079. * @return the associated data, can be null if the factory returned null.
  27080. */
  27081. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27082. if (!this._externalData) {
  27083. this._externalData = new BABYLON.StringDictionary();
  27084. }
  27085. return this._externalData.getOrAddWithFactory(key, factory);
  27086. };
  27087. /**
  27088. * Remove an externaly attached data from the Engine instance
  27089. * @param key the unique key that identifies the data
  27090. * @return true if the data was successfully removed, false if it doesn't exist
  27091. */
  27092. Scene.prototype.removeExternalData = function (key) {
  27093. return this._externalData.remove(key);
  27094. };
  27095. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27096. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27097. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27098. var step = _a[_i];
  27099. step.action(mesh, subMesh);
  27100. }
  27101. var material = subMesh.getMaterial();
  27102. if (material !== null && material !== undefined) {
  27103. // Render targets
  27104. if (material.getRenderTargetTextures !== undefined) {
  27105. if (this._processedMaterials.indexOf(material) === -1) {
  27106. this._processedMaterials.push(material);
  27107. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27108. }
  27109. }
  27110. // Dispatch
  27111. this._activeIndices.addCount(subMesh.indexCount, false);
  27112. this._renderingManager.dispatch(subMesh, mesh, material);
  27113. }
  27114. }
  27115. };
  27116. /**
  27117. * Clear the processed materials smart array preventing retention point in material dispose.
  27118. */
  27119. Scene.prototype.freeProcessedMaterials = function () {
  27120. this._processedMaterials.dispose();
  27121. };
  27122. /**
  27123. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27124. */
  27125. Scene.prototype.freeActiveMeshes = function () {
  27126. this._activeMeshes.dispose();
  27127. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27128. this.activeCamera._activeMeshes.dispose();
  27129. }
  27130. if (this.activeCameras) {
  27131. for (var i = 0; i < this.activeCameras.length; i++) {
  27132. var activeCamera = this.activeCameras[i];
  27133. if (activeCamera && activeCamera._activeMeshes) {
  27134. activeCamera._activeMeshes.dispose();
  27135. }
  27136. }
  27137. }
  27138. };
  27139. /**
  27140. * Clear the info related to rendering groups preventing retention points during dispose.
  27141. */
  27142. Scene.prototype.freeRenderingGroups = function () {
  27143. if (this._renderingManager) {
  27144. this._renderingManager.freeRenderingGroups();
  27145. }
  27146. if (this.textures) {
  27147. for (var i = 0; i < this.textures.length; i++) {
  27148. var texture = this.textures[i];
  27149. if (texture && texture.renderList) {
  27150. texture.freeRenderingGroups();
  27151. }
  27152. }
  27153. }
  27154. };
  27155. /** @hidden */
  27156. Scene.prototype._isInIntermediateRendering = function () {
  27157. return this._intermediateRendering;
  27158. };
  27159. /**
  27160. * Defines the current active mesh candidate provider
  27161. * @param provider defines the provider to use
  27162. */
  27163. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27164. this._activeMeshCandidateProvider = provider;
  27165. };
  27166. /**
  27167. * Gets the current active mesh candidate provider
  27168. * @returns the current active mesh candidate provider
  27169. */
  27170. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27171. return this._activeMeshCandidateProvider;
  27172. };
  27173. /**
  27174. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27175. * @returns the current scene
  27176. */
  27177. Scene.prototype.freezeActiveMeshes = function () {
  27178. if (!this.activeCamera) {
  27179. return this;
  27180. }
  27181. if (!this._frustumPlanes) {
  27182. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27183. }
  27184. this._evaluateActiveMeshes();
  27185. this._activeMeshesFrozen = true;
  27186. return this;
  27187. };
  27188. /**
  27189. * Use this function to restart evaluating active meshes on every frame
  27190. * @returns the current scene
  27191. */
  27192. Scene.prototype.unfreezeActiveMeshes = function () {
  27193. this._activeMeshesFrozen = false;
  27194. return this;
  27195. };
  27196. Scene.prototype._evaluateActiveMeshes = function () {
  27197. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27198. return;
  27199. }
  27200. if (!this.activeCamera) {
  27201. return;
  27202. }
  27203. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27204. this.activeCamera._activeMeshes.reset();
  27205. this._activeMeshes.reset();
  27206. this._renderingManager.reset();
  27207. this._processedMaterials.reset();
  27208. this._activeParticleSystems.reset();
  27209. this._activeSkeletons.reset();
  27210. this._softwareSkinnedMeshes.reset();
  27211. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27212. var step = _a[_i];
  27213. step.action();
  27214. }
  27215. // Meshes
  27216. var meshes;
  27217. var len;
  27218. var checkIsEnabled = true;
  27219. // Determine mesh candidates
  27220. if (this._activeMeshCandidateProvider !== undefined) {
  27221. // Use _activeMeshCandidateProvider
  27222. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27223. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27224. if (meshes !== undefined) {
  27225. len = meshes.length;
  27226. }
  27227. else {
  27228. len = 0;
  27229. }
  27230. }
  27231. else if (this._selectionOctree !== undefined) {
  27232. // Octree
  27233. var selection = this._selectionOctree.select(this._frustumPlanes);
  27234. meshes = selection.data;
  27235. len = selection.length;
  27236. }
  27237. else {
  27238. // Full scene traversal
  27239. len = this.meshes.length;
  27240. meshes = this.meshes;
  27241. }
  27242. // Check each mesh
  27243. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27244. mesh = meshes[meshIndex];
  27245. if (mesh.isBlocked) {
  27246. continue;
  27247. }
  27248. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27249. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27250. continue;
  27251. }
  27252. mesh.computeWorldMatrix();
  27253. // Intersections
  27254. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27255. this._meshesForIntersections.pushNoDuplicate(mesh);
  27256. }
  27257. // Switch to current LOD
  27258. meshLOD = mesh.getLOD(this.activeCamera);
  27259. if (meshLOD === undefined || meshLOD === null) {
  27260. continue;
  27261. }
  27262. mesh._preActivate();
  27263. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27264. this._activeMeshes.push(mesh);
  27265. this.activeCamera._activeMeshes.push(mesh);
  27266. mesh._activate(this._renderId);
  27267. if (meshLOD !== mesh) {
  27268. meshLOD._activate(this._renderId);
  27269. }
  27270. this._activeMesh(mesh, meshLOD);
  27271. }
  27272. }
  27273. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27274. // Particle systems
  27275. if (this.particlesEnabled) {
  27276. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27277. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27278. var particleSystem = this.particleSystems[particleIndex];
  27279. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27280. continue;
  27281. }
  27282. var emitter = particleSystem.emitter;
  27283. if (!emitter.position || emitter.isEnabled()) {
  27284. this._activeParticleSystems.push(particleSystem);
  27285. particleSystem.animate();
  27286. this._renderingManager.dispatchParticles(particleSystem);
  27287. }
  27288. }
  27289. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27290. }
  27291. };
  27292. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27293. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27294. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27295. mesh.skeleton.prepare();
  27296. }
  27297. if (!mesh.computeBonesUsingShaders) {
  27298. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27299. }
  27300. }
  27301. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27302. var step = _a[_i];
  27303. step.action(sourceMesh, mesh);
  27304. }
  27305. if (mesh !== undefined && mesh !== null
  27306. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27307. // Submeshes Octrees
  27308. var len;
  27309. var subMeshes;
  27310. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27311. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27312. len = intersections.length;
  27313. subMeshes = intersections.data;
  27314. }
  27315. else {
  27316. subMeshes = mesh.subMeshes;
  27317. len = subMeshes.length;
  27318. }
  27319. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27320. subMesh = subMeshes[subIndex];
  27321. this._evaluateSubMesh(subMesh, mesh);
  27322. }
  27323. }
  27324. };
  27325. /**
  27326. * Update the transform matrix to update from the current active camera
  27327. * @param force defines a boolean used to force the update even if cache is up to date
  27328. */
  27329. Scene.prototype.updateTransformMatrix = function (force) {
  27330. if (!this.activeCamera) {
  27331. return;
  27332. }
  27333. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27334. };
  27335. /**
  27336. * 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)
  27337. * @param alternateCamera defines the camera to use
  27338. */
  27339. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27340. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27341. };
  27342. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27343. if (camera && camera._skipRendering) {
  27344. return;
  27345. }
  27346. var engine = this._engine;
  27347. this.activeCamera = camera;
  27348. if (!this.activeCamera)
  27349. throw new Error("Active camera not set");
  27350. // Viewport
  27351. engine.setViewport(this.activeCamera.viewport);
  27352. // Camera
  27353. this.resetCachedMaterial();
  27354. this._renderId++;
  27355. this.updateTransformMatrix();
  27356. if (camera._alternateCamera) {
  27357. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27358. this._alternateRendering = true;
  27359. }
  27360. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27361. // Meshes
  27362. this._evaluateActiveMeshes();
  27363. // Software skinning
  27364. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27365. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27366. mesh.applySkeleton(mesh.skeleton);
  27367. }
  27368. // Render targets
  27369. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27370. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27371. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27372. }
  27373. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27374. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27375. }
  27376. if (this.renderTargetsEnabled) {
  27377. this._intermediateRendering = true;
  27378. if (this._renderTargets.length > 0) {
  27379. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27380. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27381. var renderTarget = this._renderTargets.data[renderIndex];
  27382. if (renderTarget._shouldRender()) {
  27383. this._renderId++;
  27384. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27385. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27386. }
  27387. }
  27388. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27389. this._renderId++;
  27390. }
  27391. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27392. var step = _a[_i];
  27393. step.action(this.activeCamera);
  27394. }
  27395. this._intermediateRendering = false;
  27396. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27397. }
  27398. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27399. // Prepare Frame
  27400. if (this.postProcessManager) {
  27401. this.postProcessManager._prepareFrame();
  27402. }
  27403. // Before Camera Draw
  27404. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27405. var step = _c[_b];
  27406. step.action(this.activeCamera);
  27407. }
  27408. // Render
  27409. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27410. this._renderingManager.render(null, null, true, true);
  27411. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27412. // After Camera Draw
  27413. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27414. var step = _e[_d];
  27415. step.action(this.activeCamera);
  27416. }
  27417. // Finalize frame
  27418. if (this.postProcessManager) {
  27419. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27420. }
  27421. // Reset some special arrays
  27422. this._renderTargets.reset();
  27423. this._alternateRendering = false;
  27424. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27425. };
  27426. Scene.prototype._processSubCameras = function (camera) {
  27427. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27428. this._renderForCamera(camera);
  27429. return;
  27430. }
  27431. // rig cameras
  27432. for (var index = 0; index < camera._rigCameras.length; index++) {
  27433. this._renderForCamera(camera._rigCameras[index], camera);
  27434. }
  27435. this.activeCamera = camera;
  27436. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27437. };
  27438. Scene.prototype._checkIntersections = function () {
  27439. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27440. var sourceMesh = this._meshesForIntersections.data[index];
  27441. if (!sourceMesh.actionManager) {
  27442. continue;
  27443. }
  27444. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27445. var action = sourceMesh.actionManager.actions[actionIndex];
  27446. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27447. var parameters = action.getTriggerParameter();
  27448. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27449. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27450. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27451. if (areIntersecting && currentIntersectionInProgress === -1) {
  27452. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27453. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27454. sourceMesh._intersectionsInProgress.push(otherMesh);
  27455. }
  27456. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27457. sourceMesh._intersectionsInProgress.push(otherMesh);
  27458. }
  27459. }
  27460. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27461. //They intersected, and now they don't.
  27462. //is this trigger an exit trigger? execute an event.
  27463. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27464. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27465. }
  27466. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27467. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27468. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27469. return otherMesh === parameterMesh;
  27470. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27471. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27472. }
  27473. }
  27474. }
  27475. }
  27476. }
  27477. };
  27478. /**
  27479. * Render the scene
  27480. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27481. */
  27482. Scene.prototype.render = function (updateCameras) {
  27483. if (updateCameras === void 0) { updateCameras = true; }
  27484. if (this.isDisposed) {
  27485. return;
  27486. }
  27487. // Register components that have been associated lately to the scene.
  27488. this._registerTransientComponents();
  27489. this._activeParticles.fetchNewFrame();
  27490. this._totalVertices.fetchNewFrame();
  27491. this._activeIndices.fetchNewFrame();
  27492. this._activeBones.fetchNewFrame();
  27493. this._meshesForIntersections.reset();
  27494. this.resetCachedMaterial();
  27495. this.onBeforeAnimationsObservable.notifyObservers(this);
  27496. // Actions
  27497. if (this.actionManager) {
  27498. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27499. }
  27500. //Simplification Queue
  27501. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27502. this.simplificationQueue.executeNext();
  27503. }
  27504. if (this._engine.isDeterministicLockStep()) {
  27505. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27506. var defaultFPS = (60.0 / 1000.0);
  27507. var defaultFrameTime = 1000 / 60; // frame time in MS
  27508. if (this._physicsEngine) {
  27509. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27510. }
  27511. var stepsTaken = 0;
  27512. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27513. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27514. internalSteps = Math.min(internalSteps, maxSubSteps);
  27515. do {
  27516. this.onBeforeStepObservable.notifyObservers(this);
  27517. // Animations
  27518. this._animationRatio = defaultFrameTime * defaultFPS;
  27519. this._animate();
  27520. this.onAfterAnimationsObservable.notifyObservers(this);
  27521. // Physics
  27522. if (this._physicsEngine) {
  27523. this.onBeforePhysicsObservable.notifyObservers(this);
  27524. this._physicsEngine._step(defaultFrameTime / 1000);
  27525. this.onAfterPhysicsObservable.notifyObservers(this);
  27526. }
  27527. this.onAfterStepObservable.notifyObservers(this);
  27528. this._currentStepId++;
  27529. stepsTaken++;
  27530. deltaTime -= defaultFrameTime;
  27531. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27532. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27533. }
  27534. else {
  27535. // Animations
  27536. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27537. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27538. this._animate();
  27539. this.onAfterAnimationsObservable.notifyObservers(this);
  27540. // Physics
  27541. if (this._physicsEngine) {
  27542. this.onBeforePhysicsObservable.notifyObservers(this);
  27543. this._physicsEngine._step(deltaTime / 1000.0);
  27544. this.onAfterPhysicsObservable.notifyObservers(this);
  27545. }
  27546. }
  27547. // Before camera update steps
  27548. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27549. var step = _a[_i];
  27550. step.action();
  27551. }
  27552. // Update Cameras
  27553. if (updateCameras) {
  27554. if (this.activeCameras.length > 0) {
  27555. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27556. var camera = this.activeCameras[cameraIndex];
  27557. camera.update();
  27558. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27559. // rig cameras
  27560. for (var index = 0; index < camera._rigCameras.length; index++) {
  27561. camera._rigCameras[index].update();
  27562. }
  27563. }
  27564. }
  27565. }
  27566. else if (this.activeCamera) {
  27567. this.activeCamera.update();
  27568. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27569. // rig cameras
  27570. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27571. this.activeCamera._rigCameras[index].update();
  27572. }
  27573. }
  27574. }
  27575. }
  27576. // Before render
  27577. this.onBeforeRenderObservable.notifyObservers(this);
  27578. // Customs render targets
  27579. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27580. var engine = this.getEngine();
  27581. var currentActiveCamera = this.activeCamera;
  27582. if (this.renderTargetsEnabled) {
  27583. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27584. this._intermediateRendering = true;
  27585. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27586. var renderTarget = this.customRenderTargets[customIndex];
  27587. if (renderTarget._shouldRender()) {
  27588. this._renderId++;
  27589. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27590. if (!this.activeCamera)
  27591. throw new Error("Active camera not set");
  27592. // Viewport
  27593. engine.setViewport(this.activeCamera.viewport);
  27594. // Camera
  27595. this.updateTransformMatrix();
  27596. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27597. }
  27598. }
  27599. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27600. this._intermediateRendering = false;
  27601. this._renderId++;
  27602. }
  27603. // Restore back buffer
  27604. if (this.customRenderTargets.length > 0) {
  27605. engine.restoreDefaultFramebuffer();
  27606. }
  27607. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27608. this.activeCamera = currentActiveCamera;
  27609. // Procedural textures
  27610. if (this.proceduralTexturesEnabled) {
  27611. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27612. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27613. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27614. if (proceduralTexture._shouldRender()) {
  27615. proceduralTexture.render();
  27616. }
  27617. }
  27618. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27619. }
  27620. // Clear
  27621. if (this.autoClearDepthAndStencil || this.autoClear) {
  27622. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27623. }
  27624. // Shadows
  27625. if (this.shadowsEnabled) {
  27626. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27627. var light = this.lights[lightIndex];
  27628. var shadowGenerator = light.getShadowGenerator();
  27629. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27630. var shadowMap = (shadowGenerator.getShadowMap());
  27631. if (this.textures.indexOf(shadowMap) !== -1) {
  27632. this._renderTargets.push(shadowMap);
  27633. }
  27634. }
  27635. }
  27636. }
  27637. // Depth renderer
  27638. for (var key in this._depthRenderer) {
  27639. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27640. }
  27641. // Geometry renderer
  27642. if (this._geometryBufferRenderer) {
  27643. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27644. }
  27645. // RenderPipeline
  27646. if (this._postProcessRenderPipelineManager) {
  27647. this._postProcessRenderPipelineManager.update();
  27648. }
  27649. // Multi-cameras?
  27650. if (this.activeCameras.length > 0) {
  27651. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27652. if (cameraIndex > 0) {
  27653. this._engine.clear(null, false, true, true);
  27654. }
  27655. this._processSubCameras(this.activeCameras[cameraIndex]);
  27656. }
  27657. }
  27658. else {
  27659. if (!this.activeCamera) {
  27660. throw new Error("No camera defined");
  27661. }
  27662. this._processSubCameras(this.activeCamera);
  27663. }
  27664. // Intersection checks
  27665. this._checkIntersections();
  27666. // Update the audio listener attached to the camera
  27667. if (BABYLON.AudioEngine) {
  27668. this._updateAudioParameters();
  27669. }
  27670. // After render
  27671. if (this.afterRender) {
  27672. this.afterRender();
  27673. }
  27674. this.onAfterRenderObservable.notifyObservers(this);
  27675. // Cleaning
  27676. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27677. var data = this._toBeDisposed.data[index];
  27678. if (data) {
  27679. data.dispose();
  27680. }
  27681. this._toBeDisposed[index] = null;
  27682. }
  27683. this._toBeDisposed.reset();
  27684. if (this.dumpNextRenderTargets) {
  27685. this.dumpNextRenderTargets = false;
  27686. }
  27687. this._activeBones.addCount(0, true);
  27688. this._activeIndices.addCount(0, true);
  27689. this._activeParticles.addCount(0, true);
  27690. };
  27691. Scene.prototype._updateAudioParameters = function () {
  27692. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27693. return;
  27694. }
  27695. var listeningCamera;
  27696. var audioEngine = BABYLON.Engine.audioEngine;
  27697. if (this.activeCameras.length > 0) {
  27698. listeningCamera = this.activeCameras[0];
  27699. }
  27700. else {
  27701. listeningCamera = this.activeCamera;
  27702. }
  27703. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27704. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27705. // for VR cameras
  27706. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27707. listeningCamera = listeningCamera.rigCameras[0];
  27708. }
  27709. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27710. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27711. cameraDirection.normalize();
  27712. // To avoid some errors on GearVR
  27713. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27714. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27715. }
  27716. var i;
  27717. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27718. var sound = this.mainSoundTrack.soundCollection[i];
  27719. if (sound.useCustomAttenuation) {
  27720. sound.updateDistanceFromListener();
  27721. }
  27722. }
  27723. for (i = 0; i < this.soundTracks.length; i++) {
  27724. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27725. sound = this.soundTracks[i].soundCollection[j];
  27726. if (sound.useCustomAttenuation) {
  27727. sound.updateDistanceFromListener();
  27728. }
  27729. }
  27730. }
  27731. }
  27732. };
  27733. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27734. // Audio
  27735. /**
  27736. * Gets or sets if audio support is enabled
  27737. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27738. */
  27739. get: function () {
  27740. return this._audioEnabled;
  27741. },
  27742. set: function (value) {
  27743. this._audioEnabled = value;
  27744. if (BABYLON.AudioEngine) {
  27745. if (this._audioEnabled) {
  27746. this._enableAudio();
  27747. }
  27748. else {
  27749. this._disableAudio();
  27750. }
  27751. }
  27752. },
  27753. enumerable: true,
  27754. configurable: true
  27755. });
  27756. Scene.prototype._disableAudio = function () {
  27757. var i;
  27758. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27759. this.mainSoundTrack.soundCollection[i].pause();
  27760. }
  27761. for (i = 0; i < this.soundTracks.length; i++) {
  27762. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27763. this.soundTracks[i].soundCollection[j].pause();
  27764. }
  27765. }
  27766. };
  27767. Scene.prototype._enableAudio = function () {
  27768. var i;
  27769. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27770. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27771. this.mainSoundTrack.soundCollection[i].play();
  27772. }
  27773. }
  27774. for (i = 0; i < this.soundTracks.length; i++) {
  27775. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27776. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27777. this.soundTracks[i].soundCollection[j].play();
  27778. }
  27779. }
  27780. }
  27781. };
  27782. Object.defineProperty(Scene.prototype, "headphone", {
  27783. /**
  27784. * Gets or sets if audio will be output to headphones
  27785. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27786. */
  27787. get: function () {
  27788. return this._headphone;
  27789. },
  27790. set: function (value) {
  27791. this._headphone = value;
  27792. if (BABYLON.AudioEngine) {
  27793. if (this._headphone) {
  27794. this._switchAudioModeForHeadphones();
  27795. }
  27796. else {
  27797. this._switchAudioModeForNormalSpeakers();
  27798. }
  27799. }
  27800. },
  27801. enumerable: true,
  27802. configurable: true
  27803. });
  27804. Scene.prototype._switchAudioModeForHeadphones = function () {
  27805. this.mainSoundTrack.switchPanningModelToHRTF();
  27806. for (var i = 0; i < this.soundTracks.length; i++) {
  27807. this.soundTracks[i].switchPanningModelToHRTF();
  27808. }
  27809. };
  27810. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27811. this.mainSoundTrack.switchPanningModelToEqualPower();
  27812. for (var i = 0; i < this.soundTracks.length; i++) {
  27813. this.soundTracks[i].switchPanningModelToEqualPower();
  27814. }
  27815. };
  27816. /**
  27817. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27818. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27819. * @returns the created depth renderer
  27820. */
  27821. Scene.prototype.enableDepthRenderer = function (camera) {
  27822. camera = camera || this.activeCamera;
  27823. if (!camera) {
  27824. throw "No camera available to enable depth renderer";
  27825. }
  27826. if (!this._depthRenderer[camera.id]) {
  27827. var textureType = 0;
  27828. if (this._engine.getCaps().textureHalfFloatRender) {
  27829. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27830. }
  27831. else if (this._engine.getCaps().textureFloatRender) {
  27832. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27833. }
  27834. else {
  27835. throw "Depth renderer does not support int texture type";
  27836. }
  27837. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27838. }
  27839. return this._depthRenderer[camera.id];
  27840. };
  27841. /**
  27842. * Disables a depth renderer for a given camera
  27843. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27844. */
  27845. Scene.prototype.disableDepthRenderer = function (camera) {
  27846. camera = camera || this.activeCamera;
  27847. if (!camera || !this._depthRenderer[camera.id]) {
  27848. return;
  27849. }
  27850. this._depthRenderer[camera.id].dispose();
  27851. delete this._depthRenderer[camera.id];
  27852. };
  27853. /**
  27854. * Enables a GeometryBufferRender and associates it with the scene
  27855. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27856. * @returns the GeometryBufferRenderer
  27857. */
  27858. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27859. if (ratio === void 0) { ratio = 1; }
  27860. if (this._geometryBufferRenderer) {
  27861. return this._geometryBufferRenderer;
  27862. }
  27863. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27864. if (!this._geometryBufferRenderer.isSupported) {
  27865. this._geometryBufferRenderer = null;
  27866. }
  27867. return this._geometryBufferRenderer;
  27868. };
  27869. /**
  27870. * Disables the GeometryBufferRender associated with the scene
  27871. */
  27872. Scene.prototype.disableGeometryBufferRenderer = function () {
  27873. if (!this._geometryBufferRenderer) {
  27874. return;
  27875. }
  27876. this._geometryBufferRenderer.dispose();
  27877. this._geometryBufferRenderer = null;
  27878. };
  27879. /**
  27880. * Freeze all materials
  27881. * A frozen material will not be updatable but should be faster to render
  27882. */
  27883. Scene.prototype.freezeMaterials = function () {
  27884. for (var i = 0; i < this.materials.length; i++) {
  27885. this.materials[i].freeze();
  27886. }
  27887. };
  27888. /**
  27889. * Unfreeze all materials
  27890. * A frozen material will not be updatable but should be faster to render
  27891. */
  27892. Scene.prototype.unfreezeMaterials = function () {
  27893. for (var i = 0; i < this.materials.length; i++) {
  27894. this.materials[i].unfreeze();
  27895. }
  27896. };
  27897. /**
  27898. * Releases all held ressources
  27899. */
  27900. Scene.prototype.dispose = function () {
  27901. this.beforeRender = null;
  27902. this.afterRender = null;
  27903. this.skeletons = [];
  27904. this.morphTargetManagers = [];
  27905. this._transientComponents = [];
  27906. this._isReadyForMeshStage.clear();
  27907. this._beforeEvaluateActiveMeshStage.clear();
  27908. this._evaluateSubMeshStage.clear();
  27909. this._activeMeshStage.clear();
  27910. this._cameraDrawRenderTargetStage.clear();
  27911. this._beforeCameraDrawStage.clear();
  27912. this._beforeRenderingGroupDrawStage.clear();
  27913. this._afterRenderingGroupDrawStage.clear();
  27914. this._afterCameraDrawStage.clear();
  27915. this._beforeCameraUpdateStage.clear();
  27916. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27917. var component = _a[_i];
  27918. component.dispose();
  27919. }
  27920. this.importedMeshesFiles = new Array();
  27921. this.stopAllAnimations();
  27922. this.resetCachedMaterial();
  27923. for (var key in this._depthRenderer) {
  27924. this._depthRenderer[key].dispose();
  27925. }
  27926. // Smart arrays
  27927. if (this.activeCamera) {
  27928. this.activeCamera._activeMeshes.dispose();
  27929. this.activeCamera = null;
  27930. }
  27931. this._activeMeshes.dispose();
  27932. this._renderingManager.dispose();
  27933. this._processedMaterials.dispose();
  27934. this._activeParticleSystems.dispose();
  27935. this._activeSkeletons.dispose();
  27936. this._softwareSkinnedMeshes.dispose();
  27937. this._renderTargets.dispose();
  27938. this._registeredForLateAnimationBindings.dispose();
  27939. this._meshesForIntersections.dispose();
  27940. this._toBeDisposed.dispose();
  27941. // Abort active requests
  27942. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27943. var request = _c[_b];
  27944. request.abort();
  27945. }
  27946. // Debug layer
  27947. if (this._debugLayer) {
  27948. this._debugLayer.hide();
  27949. }
  27950. // Events
  27951. this.onDisposeObservable.notifyObservers(this);
  27952. this.onDisposeObservable.clear();
  27953. this.onBeforeRenderObservable.clear();
  27954. this.onAfterRenderObservable.clear();
  27955. this.onBeforeRenderTargetsRenderObservable.clear();
  27956. this.onAfterRenderTargetsRenderObservable.clear();
  27957. this.onAfterStepObservable.clear();
  27958. this.onBeforeStepObservable.clear();
  27959. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27960. this.onAfterActiveMeshesEvaluationObservable.clear();
  27961. this.onBeforeParticlesRenderingObservable.clear();
  27962. this.onAfterParticlesRenderingObservable.clear();
  27963. this.onBeforeSpritesRenderingObservable.clear();
  27964. this.onAfterSpritesRenderingObservable.clear();
  27965. this.onBeforeDrawPhaseObservable.clear();
  27966. this.onAfterDrawPhaseObservable.clear();
  27967. this.onBeforePhysicsObservable.clear();
  27968. this.onAfterPhysicsObservable.clear();
  27969. this.onBeforeAnimationsObservable.clear();
  27970. this.onAfterAnimationsObservable.clear();
  27971. this.onDataLoadedObservable.clear();
  27972. this.onBeforeRenderingGroupObservable.clear();
  27973. this.onAfterRenderingGroupObservable.clear();
  27974. this.detachControl();
  27975. // Release sounds & sounds tracks
  27976. if (BABYLON.AudioEngine) {
  27977. this.disposeSounds();
  27978. }
  27979. // VR Helper
  27980. if (this.VRHelper) {
  27981. this.VRHelper.dispose();
  27982. }
  27983. // Detach cameras
  27984. var canvas = this._engine.getRenderingCanvas();
  27985. if (canvas) {
  27986. var index;
  27987. for (index = 0; index < this.cameras.length; index++) {
  27988. this.cameras[index].detachControl(canvas);
  27989. }
  27990. }
  27991. // Release animation groups
  27992. while (this.animationGroups.length) {
  27993. this.animationGroups[0].dispose();
  27994. }
  27995. // Release lights
  27996. while (this.lights.length) {
  27997. this.lights[0].dispose();
  27998. }
  27999. // Release meshes
  28000. while (this.meshes.length) {
  28001. this.meshes[0].dispose(true);
  28002. }
  28003. while (this.transformNodes.length) {
  28004. this.removeTransformNode(this.transformNodes[0]);
  28005. }
  28006. // Release cameras
  28007. while (this.cameras.length) {
  28008. this.cameras[0].dispose();
  28009. }
  28010. // Release materials
  28011. if (this.defaultMaterial) {
  28012. this.defaultMaterial.dispose();
  28013. }
  28014. while (this.multiMaterials.length) {
  28015. this.multiMaterials[0].dispose();
  28016. }
  28017. while (this.materials.length) {
  28018. this.materials[0].dispose();
  28019. }
  28020. // Release particles
  28021. while (this.particleSystems.length) {
  28022. this.particleSystems[0].dispose();
  28023. }
  28024. // Release sprites
  28025. while (this.spriteManagers.length) {
  28026. this.spriteManagers[0].dispose();
  28027. }
  28028. // Release postProcesses
  28029. while (this.postProcesses.length) {
  28030. this.postProcesses[0].dispose();
  28031. }
  28032. // Release textures
  28033. while (this.textures.length) {
  28034. this.textures[0].dispose();
  28035. }
  28036. // Release UBO
  28037. this._sceneUbo.dispose();
  28038. if (this._alternateSceneUbo) {
  28039. this._alternateSceneUbo.dispose();
  28040. }
  28041. // Post-processes
  28042. this.postProcessManager.dispose();
  28043. if (this._postProcessRenderPipelineManager) {
  28044. this._postProcessRenderPipelineManager.dispose();
  28045. }
  28046. // Physics
  28047. if (this._physicsEngine) {
  28048. this.disablePhysicsEngine();
  28049. }
  28050. // Remove from engine
  28051. index = this._engine.scenes.indexOf(this);
  28052. if (index > -1) {
  28053. this._engine.scenes.splice(index, 1);
  28054. }
  28055. this._engine.wipeCaches(true);
  28056. this._isDisposed = true;
  28057. };
  28058. Object.defineProperty(Scene.prototype, "isDisposed", {
  28059. /**
  28060. * Gets if the scene is already disposed
  28061. */
  28062. get: function () {
  28063. return this._isDisposed;
  28064. },
  28065. enumerable: true,
  28066. configurable: true
  28067. });
  28068. /**
  28069. * Releases sounds & soundtracks
  28070. */
  28071. Scene.prototype.disposeSounds = function () {
  28072. if (!this._mainSoundTrack) {
  28073. return;
  28074. }
  28075. this.mainSoundTrack.dispose();
  28076. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28077. this.soundTracks[scIndex].dispose();
  28078. }
  28079. };
  28080. /**
  28081. * Call this function to reduce memory footprint of the scene.
  28082. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28083. */
  28084. Scene.prototype.clearCachedVertexData = function () {
  28085. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28086. var mesh = this.meshes[meshIndex];
  28087. var geometry = mesh.geometry;
  28088. if (geometry) {
  28089. geometry._indices = [];
  28090. for (var vbName in geometry._vertexBuffers) {
  28091. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28092. continue;
  28093. }
  28094. geometry._vertexBuffers[vbName]._buffer._data = null;
  28095. }
  28096. }
  28097. }
  28098. };
  28099. /**
  28100. * This function will remove the local cached buffer data from texture.
  28101. * It will save memory but will prevent the texture from being rebuilt
  28102. */
  28103. Scene.prototype.cleanCachedTextureBuffer = function () {
  28104. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28105. var baseTexture = _a[_i];
  28106. var buffer = baseTexture._buffer;
  28107. if (buffer) {
  28108. baseTexture._buffer = null;
  28109. }
  28110. }
  28111. };
  28112. // Octrees
  28113. /**
  28114. * Get the world extend vectors with an optional filter
  28115. *
  28116. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28117. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28118. */
  28119. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28120. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28121. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28122. filterPredicate = filterPredicate || (function () { return true; });
  28123. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28124. mesh.computeWorldMatrix(true);
  28125. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28126. return;
  28127. }
  28128. var boundingInfo = mesh.getBoundingInfo();
  28129. var minBox = boundingInfo.boundingBox.minimumWorld;
  28130. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28131. BABYLON.Tools.CheckExtends(minBox, min, max);
  28132. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28133. });
  28134. return {
  28135. min: min,
  28136. max: max
  28137. };
  28138. };
  28139. /**
  28140. * Creates or updates the octree used to boost selection (picking)
  28141. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28142. * @param maxCapacity defines the maximum capacity per leaf
  28143. * @param maxDepth defines the maximum depth of the octree
  28144. * @returns an octree of AbstractMesh
  28145. */
  28146. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28147. if (maxCapacity === void 0) { maxCapacity = 64; }
  28148. if (maxDepth === void 0) { maxDepth = 2; }
  28149. if (!this._selectionOctree) {
  28150. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28151. }
  28152. var worldExtends = this.getWorldExtends();
  28153. // Update octree
  28154. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28155. return this._selectionOctree;
  28156. };
  28157. // Picking
  28158. /**
  28159. * Creates a ray that can be used to pick in the scene
  28160. * @param x defines the x coordinate of the origin (on-screen)
  28161. * @param y defines the y coordinate of the origin (on-screen)
  28162. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28163. * @param camera defines the camera to use for the picking
  28164. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28165. * @returns a Ray
  28166. */
  28167. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28168. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28169. var result = BABYLON.Ray.Zero();
  28170. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28171. return result;
  28172. };
  28173. /**
  28174. * Creates a ray that can be used to pick in the scene
  28175. * @param x defines the x coordinate of the origin (on-screen)
  28176. * @param y defines the y coordinate of the origin (on-screen)
  28177. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28178. * @param result defines the ray where to store the picking ray
  28179. * @param camera defines the camera to use for the picking
  28180. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28181. * @returns the current scene
  28182. */
  28183. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28184. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28185. var engine = this._engine;
  28186. if (!camera) {
  28187. if (!this.activeCamera)
  28188. throw new Error("Active camera not set");
  28189. camera = this.activeCamera;
  28190. }
  28191. var cameraViewport = camera.viewport;
  28192. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28193. // Moving coordinates to local viewport world
  28194. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28195. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28196. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28197. return this;
  28198. };
  28199. /**
  28200. * Creates a ray that can be used to pick in the scene
  28201. * @param x defines the x coordinate of the origin (on-screen)
  28202. * @param y defines the y coordinate of the origin (on-screen)
  28203. * @param camera defines the camera to use for the picking
  28204. * @returns a Ray
  28205. */
  28206. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28207. var result = BABYLON.Ray.Zero();
  28208. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28209. return result;
  28210. };
  28211. /**
  28212. * Creates a ray that can be used to pick in the scene
  28213. * @param x defines the x coordinate of the origin (on-screen)
  28214. * @param y defines the y coordinate of the origin (on-screen)
  28215. * @param result defines the ray where to store the picking ray
  28216. * @param camera defines the camera to use for the picking
  28217. * @returns the current scene
  28218. */
  28219. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28220. if (!BABYLON.PickingInfo) {
  28221. return this;
  28222. }
  28223. var engine = this._engine;
  28224. if (!camera) {
  28225. if (!this.activeCamera)
  28226. throw new Error("Active camera not set");
  28227. camera = this.activeCamera;
  28228. }
  28229. var cameraViewport = camera.viewport;
  28230. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28231. var identity = BABYLON.Matrix.Identity();
  28232. // Moving coordinates to local viewport world
  28233. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28234. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28235. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28236. return this;
  28237. };
  28238. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28239. if (!BABYLON.PickingInfo) {
  28240. return null;
  28241. }
  28242. var pickingInfo = null;
  28243. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28244. var mesh = this.meshes[meshIndex];
  28245. if (predicate) {
  28246. if (!predicate(mesh)) {
  28247. continue;
  28248. }
  28249. }
  28250. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28251. continue;
  28252. }
  28253. var world = mesh.getWorldMatrix();
  28254. var ray = rayFunction(world);
  28255. var result = mesh.intersects(ray, fastCheck);
  28256. if (!result || !result.hit)
  28257. continue;
  28258. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28259. continue;
  28260. pickingInfo = result;
  28261. if (fastCheck) {
  28262. break;
  28263. }
  28264. }
  28265. return pickingInfo || new BABYLON.PickingInfo();
  28266. };
  28267. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28268. if (!BABYLON.PickingInfo) {
  28269. return null;
  28270. }
  28271. var pickingInfos = new Array();
  28272. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28273. var mesh = this.meshes[meshIndex];
  28274. if (predicate) {
  28275. if (!predicate(mesh)) {
  28276. continue;
  28277. }
  28278. }
  28279. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28280. continue;
  28281. }
  28282. var world = mesh.getWorldMatrix();
  28283. var ray = rayFunction(world);
  28284. var result = mesh.intersects(ray, false);
  28285. if (!result || !result.hit)
  28286. continue;
  28287. pickingInfos.push(result);
  28288. }
  28289. return pickingInfos;
  28290. };
  28291. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28292. if (!BABYLON.PickingInfo) {
  28293. return null;
  28294. }
  28295. var pickingInfo = null;
  28296. if (!camera) {
  28297. if (!this.activeCamera) {
  28298. return null;
  28299. }
  28300. camera = this.activeCamera;
  28301. }
  28302. if (this.spriteManagers.length > 0) {
  28303. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28304. var spriteManager = this.spriteManagers[spriteIndex];
  28305. if (!spriteManager.isPickable) {
  28306. continue;
  28307. }
  28308. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28309. if (!result || !result.hit)
  28310. continue;
  28311. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28312. continue;
  28313. pickingInfo = result;
  28314. if (fastCheck) {
  28315. break;
  28316. }
  28317. }
  28318. }
  28319. return pickingInfo || new BABYLON.PickingInfo();
  28320. };
  28321. /** Launch a ray to try to pick a mesh in the scene
  28322. * @param x position on screen
  28323. * @param y position on screen
  28324. * @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
  28325. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28326. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28327. * @returns a PickingInfo
  28328. */
  28329. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28330. var _this = this;
  28331. if (!BABYLON.PickingInfo) {
  28332. return null;
  28333. }
  28334. var result = this._internalPick(function (world) {
  28335. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28336. return _this._tempPickingRay;
  28337. }, predicate, fastCheck);
  28338. if (result) {
  28339. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28340. }
  28341. return result;
  28342. };
  28343. /** Launch a ray to try to pick a sprite in the scene
  28344. * @param x position on screen
  28345. * @param y position on screen
  28346. * @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
  28347. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28348. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28349. * @returns a PickingInfo
  28350. */
  28351. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28352. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28353. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28354. };
  28355. /** Use the given ray to pick a mesh in the scene
  28356. * @param ray The ray to use to pick meshes
  28357. * @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
  28358. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28359. * @returns a PickingInfo
  28360. */
  28361. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28362. var _this = this;
  28363. var result = this._internalPick(function (world) {
  28364. if (!_this._pickWithRayInverseMatrix) {
  28365. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28366. }
  28367. world.invertToRef(_this._pickWithRayInverseMatrix);
  28368. if (!_this._cachedRayForTransform) {
  28369. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28370. }
  28371. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28372. return _this._cachedRayForTransform;
  28373. }, predicate, fastCheck);
  28374. if (result) {
  28375. result.ray = ray;
  28376. }
  28377. return result;
  28378. };
  28379. /**
  28380. * Launch a ray to try to pick a mesh in the scene
  28381. * @param x X position on screen
  28382. * @param y Y position on screen
  28383. * @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
  28384. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28385. * @returns an array of PickingInfo
  28386. */
  28387. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28388. var _this = this;
  28389. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28390. };
  28391. /**
  28392. * Launch a ray to try to pick a mesh in the scene
  28393. * @param ray Ray to use
  28394. * @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
  28395. * @returns an array of PickingInfo
  28396. */
  28397. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28398. var _this = this;
  28399. return this._internalMultiPick(function (world) {
  28400. if (!_this._pickWithRayInverseMatrix) {
  28401. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28402. }
  28403. world.invertToRef(_this._pickWithRayInverseMatrix);
  28404. if (!_this._cachedRayForTransform) {
  28405. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28406. }
  28407. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28408. return _this._cachedRayForTransform;
  28409. }, predicate);
  28410. };
  28411. /**
  28412. * Force the value of meshUnderPointer
  28413. * @param mesh defines the mesh to use
  28414. */
  28415. Scene.prototype.setPointerOverMesh = function (mesh) {
  28416. if (this._pointerOverMesh === mesh) {
  28417. return;
  28418. }
  28419. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28420. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28421. }
  28422. this._pointerOverMesh = mesh;
  28423. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28424. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28425. }
  28426. };
  28427. /**
  28428. * Gets the mesh under the pointer
  28429. * @returns a Mesh or null if no mesh is under the pointer
  28430. */
  28431. Scene.prototype.getPointerOverMesh = function () {
  28432. return this._pointerOverMesh;
  28433. };
  28434. /**
  28435. * Force the sprite under the pointer
  28436. * @param sprite defines the sprite to use
  28437. */
  28438. Scene.prototype.setPointerOverSprite = function (sprite) {
  28439. if (this._pointerOverSprite === sprite) {
  28440. return;
  28441. }
  28442. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28443. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28444. }
  28445. this._pointerOverSprite = sprite;
  28446. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28447. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28448. }
  28449. };
  28450. /**
  28451. * Gets the sprite under the pointer
  28452. * @returns a Sprite or null if no sprite is under the pointer
  28453. */
  28454. Scene.prototype.getPointerOverSprite = function () {
  28455. return this._pointerOverSprite;
  28456. };
  28457. // Physics
  28458. /**
  28459. * Gets the current physics engine
  28460. * @returns a PhysicsEngine or null if none attached
  28461. */
  28462. Scene.prototype.getPhysicsEngine = function () {
  28463. return this._physicsEngine;
  28464. };
  28465. /**
  28466. * Enables physics to the current scene
  28467. * @param gravity defines the scene's gravity for the physics engine
  28468. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28469. * @return a boolean indicating if the physics engine was initialized
  28470. */
  28471. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28472. if (gravity === void 0) { gravity = null; }
  28473. if (this._physicsEngine) {
  28474. return true;
  28475. }
  28476. try {
  28477. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28478. return true;
  28479. }
  28480. catch (e) {
  28481. BABYLON.Tools.Error(e.message);
  28482. return false;
  28483. }
  28484. };
  28485. /**
  28486. * Disables and disposes the physics engine associated with the scene
  28487. */
  28488. Scene.prototype.disablePhysicsEngine = function () {
  28489. if (!this._physicsEngine) {
  28490. return;
  28491. }
  28492. this._physicsEngine.dispose();
  28493. this._physicsEngine = null;
  28494. };
  28495. /**
  28496. * Gets a boolean indicating if there is an active physics engine
  28497. * @returns a boolean indicating if there is an active physics engine
  28498. */
  28499. Scene.prototype.isPhysicsEnabled = function () {
  28500. return this._physicsEngine !== undefined;
  28501. };
  28502. /**
  28503. * Deletes a physics compound impostor
  28504. * @param compound defines the compound to delete
  28505. */
  28506. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28507. var mesh = compound.parts[0].mesh;
  28508. if (mesh.physicsImpostor) {
  28509. mesh.physicsImpostor.dispose( /*true*/);
  28510. mesh.physicsImpostor = null;
  28511. }
  28512. };
  28513. // Misc.
  28514. /** @hidden */
  28515. Scene.prototype._rebuildGeometries = function () {
  28516. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28517. var geometry = _a[_i];
  28518. geometry._rebuild();
  28519. }
  28520. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28521. var mesh = _c[_b];
  28522. mesh._rebuild();
  28523. }
  28524. if (this.postProcessManager) {
  28525. this.postProcessManager._rebuild();
  28526. }
  28527. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28528. var component = _e[_d];
  28529. component.rebuild();
  28530. }
  28531. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28532. var system = _g[_f];
  28533. system.rebuild();
  28534. }
  28535. if (this._postProcessRenderPipelineManager) {
  28536. this._postProcessRenderPipelineManager._rebuild();
  28537. }
  28538. };
  28539. /** @hidden */
  28540. Scene.prototype._rebuildTextures = function () {
  28541. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28542. var texture = _a[_i];
  28543. texture._rebuild();
  28544. }
  28545. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28546. };
  28547. /**
  28548. * Creates a default light for the scene.
  28549. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28550. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28551. */
  28552. Scene.prototype.createDefaultLight = function (replace) {
  28553. if (replace === void 0) { replace = false; }
  28554. // Dispose existing light in replace mode.
  28555. if (replace) {
  28556. if (this.lights) {
  28557. for (var i = 0; i < this.lights.length; i++) {
  28558. this.lights[i].dispose();
  28559. }
  28560. }
  28561. }
  28562. // Light
  28563. if (this.lights.length === 0) {
  28564. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28565. }
  28566. };
  28567. /**
  28568. * Creates a default camera for the scene.
  28569. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28570. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28571. * @param replace has default false, when true replaces the active camera in the scene
  28572. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28573. */
  28574. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28575. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28576. if (replace === void 0) { replace = false; }
  28577. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28578. // Dispose existing camera in replace mode.
  28579. if (replace) {
  28580. if (this.activeCamera) {
  28581. this.activeCamera.dispose();
  28582. this.activeCamera = null;
  28583. }
  28584. }
  28585. // Camera
  28586. if (!this.activeCamera) {
  28587. var worldExtends = this.getWorldExtends();
  28588. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28589. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28590. var camera;
  28591. var radius = worldSize.length() * 1.5;
  28592. // empty scene scenario!
  28593. if (!isFinite(radius)) {
  28594. radius = 1;
  28595. worldCenter.copyFromFloats(0, 0, 0);
  28596. }
  28597. if (createArcRotateCamera) {
  28598. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28599. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28600. arcRotateCamera.wheelPrecision = 100 / radius;
  28601. camera = arcRotateCamera;
  28602. }
  28603. else {
  28604. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28605. freeCamera.setTarget(worldCenter);
  28606. camera = freeCamera;
  28607. }
  28608. camera.minZ = radius * 0.01;
  28609. camera.maxZ = radius * 1000;
  28610. camera.speed = radius * 0.2;
  28611. this.activeCamera = camera;
  28612. var canvas = this.getEngine().getRenderingCanvas();
  28613. if (attachCameraControls && canvas) {
  28614. camera.attachControl(canvas);
  28615. }
  28616. }
  28617. };
  28618. /**
  28619. * Creates a default camera and a default light.
  28620. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28621. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28622. * @param replace has the default false, when true replaces the active camera/light in the scene
  28623. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28624. */
  28625. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28626. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28627. if (replace === void 0) { replace = false; }
  28628. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28629. this.createDefaultLight(replace);
  28630. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28631. };
  28632. /**
  28633. * Creates a new sky box
  28634. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28635. * @param environmentTexture defines the texture to use as environment texture
  28636. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28637. * @param scale defines the overall scale of the skybox
  28638. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28639. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28640. * @returns a new mesh holding the sky box
  28641. */
  28642. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28643. if (pbr === void 0) { pbr = false; }
  28644. if (scale === void 0) { scale = 1000; }
  28645. if (blur === void 0) { blur = 0; }
  28646. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28647. if (!environmentTexture) {
  28648. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28649. return null;
  28650. }
  28651. if (setGlobalEnvTexture) {
  28652. if (environmentTexture) {
  28653. this.environmentTexture = environmentTexture;
  28654. }
  28655. }
  28656. // Skybox
  28657. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28658. if (pbr) {
  28659. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28660. hdrSkyboxMaterial.backFaceCulling = false;
  28661. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28662. if (hdrSkyboxMaterial.reflectionTexture) {
  28663. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28664. }
  28665. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28666. hdrSkyboxMaterial.disableLighting = true;
  28667. hdrSkyboxMaterial.twoSidedLighting = true;
  28668. hdrSkybox.infiniteDistance = true;
  28669. hdrSkybox.material = hdrSkyboxMaterial;
  28670. }
  28671. else {
  28672. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28673. skyboxMaterial.backFaceCulling = false;
  28674. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28675. if (skyboxMaterial.reflectionTexture) {
  28676. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28677. }
  28678. skyboxMaterial.disableLighting = true;
  28679. hdrSkybox.infiniteDistance = true;
  28680. hdrSkybox.material = skyboxMaterial;
  28681. }
  28682. return hdrSkybox;
  28683. };
  28684. /**
  28685. * Creates a new environment
  28686. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28687. * @param options defines the options you can use to configure the environment
  28688. * @returns the new EnvironmentHelper
  28689. */
  28690. Scene.prototype.createDefaultEnvironment = function (options) {
  28691. if (BABYLON.EnvironmentHelper) {
  28692. return new BABYLON.EnvironmentHelper(options, this);
  28693. }
  28694. return null;
  28695. };
  28696. /**
  28697. * Creates a new VREXperienceHelper
  28698. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28699. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28700. * @returns a new VREXperienceHelper
  28701. */
  28702. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28703. if (webVROptions === void 0) { webVROptions = {}; }
  28704. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28705. };
  28706. // Tags
  28707. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28708. if (tagsQuery === undefined) {
  28709. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28710. return list;
  28711. }
  28712. var listByTags = [];
  28713. forEach = forEach || (function (item) { return; });
  28714. for (var i in list) {
  28715. var item = list[i];
  28716. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28717. listByTags.push(item);
  28718. forEach(item);
  28719. }
  28720. }
  28721. return listByTags;
  28722. };
  28723. /**
  28724. * Get a list of meshes by tags
  28725. * @param tagsQuery defines the tags query to use
  28726. * @param forEach defines a predicate used to filter results
  28727. * @returns an array of Mesh
  28728. */
  28729. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28730. return this._getByTags(this.meshes, tagsQuery, forEach);
  28731. };
  28732. /**
  28733. * Get a list of cameras by tags
  28734. * @param tagsQuery defines the tags query to use
  28735. * @param forEach defines a predicate used to filter results
  28736. * @returns an array of Camera
  28737. */
  28738. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28739. return this._getByTags(this.cameras, tagsQuery, forEach);
  28740. };
  28741. /**
  28742. * Get a list of lights by tags
  28743. * @param tagsQuery defines the tags query to use
  28744. * @param forEach defines a predicate used to filter results
  28745. * @returns an array of Light
  28746. */
  28747. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28748. return this._getByTags(this.lights, tagsQuery, forEach);
  28749. };
  28750. /**
  28751. * Get a list of materials by tags
  28752. * @param tagsQuery defines the tags query to use
  28753. * @param forEach defines a predicate used to filter results
  28754. * @returns an array of Material
  28755. */
  28756. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28757. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28758. };
  28759. /**
  28760. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28761. * This allowed control for front to back rendering or reversly depending of the special needs.
  28762. *
  28763. * @param renderingGroupId The rendering group id corresponding to its index
  28764. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28765. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28766. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28767. */
  28768. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28769. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28770. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28771. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28772. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28773. };
  28774. /**
  28775. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28776. *
  28777. * @param renderingGroupId The rendering group id corresponding to its index
  28778. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28779. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28780. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28781. */
  28782. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28783. if (depth === void 0) { depth = true; }
  28784. if (stencil === void 0) { stencil = true; }
  28785. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28786. };
  28787. /**
  28788. * Gets the current auto clear configuration for one rendering group of the rendering
  28789. * manager.
  28790. * @param index the rendering group index to get the information for
  28791. * @returns The auto clear setup for the requested rendering group
  28792. */
  28793. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28794. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28795. };
  28796. /**
  28797. * Will flag all materials as dirty to trigger new shader compilation
  28798. * @param flag defines the flag used to specify which material part must be marked as dirty
  28799. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28800. */
  28801. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28802. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28803. var material = _a[_i];
  28804. if (predicate && !predicate(material)) {
  28805. continue;
  28806. }
  28807. material.markAsDirty(flag);
  28808. }
  28809. };
  28810. /** @hidden */
  28811. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28812. var _this = this;
  28813. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28814. this._activeRequests.push(request);
  28815. request.onCompleteObservable.add(function (request) {
  28816. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28817. });
  28818. return request;
  28819. };
  28820. /** @hidden */
  28821. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28822. var _this = this;
  28823. return new Promise(function (resolve, reject) {
  28824. _this._loadFile(url, function (data) {
  28825. resolve(data);
  28826. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28827. reject(exception);
  28828. });
  28829. });
  28830. };
  28831. // Statics
  28832. Scene._FOGMODE_NONE = 0;
  28833. Scene._FOGMODE_EXP = 1;
  28834. Scene._FOGMODE_EXP2 = 2;
  28835. Scene._FOGMODE_LINEAR = 3;
  28836. Scene._uniqueIdCounter = 0;
  28837. /**
  28838. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28839. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28840. */
  28841. Scene.MinDeltaTime = 1.0;
  28842. /**
  28843. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28844. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28845. */
  28846. Scene.MaxDeltaTime = 1000.0;
  28847. /** The distance in pixel that you have to move to prevent some events */
  28848. Scene.DragMovementThreshold = 10; // in pixels
  28849. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28850. Scene.LongPressDelay = 500; // in milliseconds
  28851. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28852. Scene.DoubleClickDelay = 300; // in milliseconds
  28853. /** If you need to check double click without raising a single click at first click, enable this flag */
  28854. Scene.ExclusiveDoubleClickMode = false;
  28855. return Scene;
  28856. }(BABYLON.AbstractScene));
  28857. BABYLON.Scene = Scene;
  28858. })(BABYLON || (BABYLON = {}));
  28859. //# sourceMappingURL=babylon.scene.js.map
  28860. var BABYLON;
  28861. (function (BABYLON) {
  28862. /**
  28863. * Set of assets to keep when moving a scene into an asset container.
  28864. */
  28865. var KeepAssets = /** @class */ (function (_super) {
  28866. __extends(KeepAssets, _super);
  28867. function KeepAssets() {
  28868. return _super !== null && _super.apply(this, arguments) || this;
  28869. }
  28870. return KeepAssets;
  28871. }(BABYLON.AbstractScene));
  28872. BABYLON.KeepAssets = KeepAssets;
  28873. /**
  28874. * Container with a set of assets that can be added or removed from a scene.
  28875. */
  28876. var AssetContainer = /** @class */ (function (_super) {
  28877. __extends(AssetContainer, _super);
  28878. /**
  28879. * Instantiates an AssetContainer.
  28880. * @param scene The scene the AssetContainer belongs to.
  28881. */
  28882. function AssetContainer(scene) {
  28883. var _this = _super.call(this) || this;
  28884. _this.scene = scene;
  28885. return _this;
  28886. }
  28887. /**
  28888. * Adds all the assets from the container to the scene.
  28889. */
  28890. AssetContainer.prototype.addAllToScene = function () {
  28891. var _this = this;
  28892. this.cameras.forEach(function (o) {
  28893. _this.scene.addCamera(o);
  28894. });
  28895. this.lights.forEach(function (o) {
  28896. _this.scene.addLight(o);
  28897. });
  28898. this.meshes.forEach(function (o) {
  28899. _this.scene.addMesh(o);
  28900. });
  28901. this.skeletons.forEach(function (o) {
  28902. _this.scene.addSkeleton(o);
  28903. });
  28904. this.animations.forEach(function (o) {
  28905. _this.scene.addAnimation(o);
  28906. });
  28907. this.animationGroups.forEach(function (o) {
  28908. _this.scene.addAnimationGroup(o);
  28909. });
  28910. this.multiMaterials.forEach(function (o) {
  28911. _this.scene.addMultiMaterial(o);
  28912. });
  28913. this.materials.forEach(function (o) {
  28914. _this.scene.addMaterial(o);
  28915. });
  28916. this.morphTargetManagers.forEach(function (o) {
  28917. _this.scene.addMorphTargetManager(o);
  28918. });
  28919. this.geometries.forEach(function (o) {
  28920. _this.scene.addGeometry(o);
  28921. });
  28922. this.transformNodes.forEach(function (o) {
  28923. _this.scene.addTransformNode(o);
  28924. });
  28925. this.actionManagers.forEach(function (o) {
  28926. _this.scene.addActionManager(o);
  28927. });
  28928. this.sounds.forEach(function (o) {
  28929. o.play();
  28930. o.autoplay = true;
  28931. _this.scene.mainSoundTrack.AddSound(o);
  28932. });
  28933. this.textures.forEach(function (o) {
  28934. _this.scene.addTexture(o);
  28935. });
  28936. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28937. var component = _a[_i];
  28938. component.addFromContainer(this.scene);
  28939. }
  28940. };
  28941. /**
  28942. * Removes all the assets in the container from the scene
  28943. */
  28944. AssetContainer.prototype.removeAllFromScene = function () {
  28945. var _this = this;
  28946. this.cameras.forEach(function (o) {
  28947. _this.scene.removeCamera(o);
  28948. });
  28949. this.lights.forEach(function (o) {
  28950. _this.scene.removeLight(o);
  28951. });
  28952. this.meshes.forEach(function (o) {
  28953. _this.scene.removeMesh(o);
  28954. });
  28955. this.skeletons.forEach(function (o) {
  28956. _this.scene.removeSkeleton(o);
  28957. });
  28958. this.animations.forEach(function (o) {
  28959. _this.scene.removeAnimation(o);
  28960. });
  28961. this.animationGroups.forEach(function (o) {
  28962. _this.scene.removeAnimationGroup(o);
  28963. });
  28964. this.multiMaterials.forEach(function (o) {
  28965. _this.scene.removeMultiMaterial(o);
  28966. });
  28967. this.materials.forEach(function (o) {
  28968. _this.scene.removeMaterial(o);
  28969. });
  28970. this.morphTargetManagers.forEach(function (o) {
  28971. _this.scene.removeMorphTargetManager(o);
  28972. });
  28973. this.geometries.forEach(function (o) {
  28974. _this.scene.removeGeometry(o);
  28975. });
  28976. this.transformNodes.forEach(function (o) {
  28977. _this.scene.removeTransformNode(o);
  28978. });
  28979. this.actionManagers.forEach(function (o) {
  28980. _this.scene.removeActionManager(o);
  28981. });
  28982. this.sounds.forEach(function (o) {
  28983. o.stop();
  28984. o.autoplay = false;
  28985. _this.scene.mainSoundTrack.RemoveSound(o);
  28986. });
  28987. this.textures.forEach(function (o) {
  28988. _this.scene.removeTexture(o);
  28989. });
  28990. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28991. var component = _a[_i];
  28992. component.removeFromContainer(this.scene);
  28993. }
  28994. };
  28995. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28996. if (!sourceAssets) {
  28997. return;
  28998. }
  28999. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29000. var asset = sourceAssets_1[_i];
  29001. var move = true;
  29002. if (keepAssets) {
  29003. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29004. var keepAsset = keepAssets_1[_a];
  29005. if (asset === keepAsset) {
  29006. move = false;
  29007. break;
  29008. }
  29009. }
  29010. }
  29011. if (move) {
  29012. targetAssets.push(asset);
  29013. }
  29014. }
  29015. };
  29016. /**
  29017. * Removes all the assets contained in the scene and adds them to the container.
  29018. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29019. */
  29020. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29021. if (keepAssets === undefined) {
  29022. keepAssets = new KeepAssets();
  29023. }
  29024. for (var key in this) {
  29025. if (this.hasOwnProperty(key)) {
  29026. this[key] = this[key] || [];
  29027. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29028. }
  29029. }
  29030. this.removeAllFromScene();
  29031. };
  29032. /**
  29033. * 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.
  29034. * @returns the root mesh
  29035. */
  29036. AssetContainer.prototype.createRootMesh = function () {
  29037. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29038. this.meshes.forEach(function (m) {
  29039. if (!m.parent) {
  29040. rootMesh.addChild(m);
  29041. }
  29042. });
  29043. this.meshes.unshift(rootMesh);
  29044. return rootMesh;
  29045. };
  29046. return AssetContainer;
  29047. }(BABYLON.AbstractScene));
  29048. BABYLON.AssetContainer = AssetContainer;
  29049. })(BABYLON || (BABYLON = {}));
  29050. //# sourceMappingURL=babylon.assetContainer.js.map
  29051. var BABYLON;
  29052. (function (BABYLON) {
  29053. var Buffer = /** @class */ (function () {
  29054. /**
  29055. * Constructor
  29056. * @param engine the engine
  29057. * @param data the data to use for this buffer
  29058. * @param updatable whether the data is updatable
  29059. * @param stride the stride (optional)
  29060. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29061. * @param instanced whether the buffer is instanced (optional)
  29062. * @param useBytes set to true if the stride in in bytes (optional)
  29063. */
  29064. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29065. if (stride === void 0) { stride = 0; }
  29066. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29067. if (instanced === void 0) { instanced = false; }
  29068. if (useBytes === void 0) { useBytes = false; }
  29069. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29070. this._engine = engine.getScene().getEngine();
  29071. }
  29072. else {
  29073. this._engine = engine;
  29074. }
  29075. this._updatable = updatable;
  29076. this._instanced = instanced;
  29077. this._data = data;
  29078. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29079. if (!postponeInternalCreation) { // by default
  29080. this.create();
  29081. }
  29082. }
  29083. /**
  29084. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29085. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29086. * @param offset defines offset in the buffer (0 by default)
  29087. * @param size defines the size in floats of attributes (position is 3 for instance)
  29088. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29089. * @param instanced defines if the vertex buffer contains indexed data
  29090. * @param useBytes defines if the offset and stride are in bytes
  29091. * @returns the new vertex buffer
  29092. */
  29093. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29094. if (useBytes === void 0) { useBytes = false; }
  29095. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29096. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29097. // a lot of these parameters are ignored as they are overriden by the buffer
  29098. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29099. };
  29100. // Properties
  29101. Buffer.prototype.isUpdatable = function () {
  29102. return this._updatable;
  29103. };
  29104. Buffer.prototype.getData = function () {
  29105. return this._data;
  29106. };
  29107. Buffer.prototype.getBuffer = function () {
  29108. return this._buffer;
  29109. };
  29110. /**
  29111. * Gets the stride in float32 units (i.e. byte stride / 4).
  29112. * May not be an integer if the byte stride is not divisible by 4.
  29113. * DEPRECATED. Use byteStride instead.
  29114. * @returns the stride in float32 units
  29115. */
  29116. Buffer.prototype.getStrideSize = function () {
  29117. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29118. };
  29119. // Methods
  29120. Buffer.prototype.create = function (data) {
  29121. if (data === void 0) { data = null; }
  29122. if (!data && this._buffer) {
  29123. return; // nothing to do
  29124. }
  29125. data = data || this._data;
  29126. if (!data) {
  29127. return;
  29128. }
  29129. if (!this._buffer) { // create buffer
  29130. if (this._updatable) {
  29131. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29132. this._data = data;
  29133. }
  29134. else {
  29135. this._buffer = this._engine.createVertexBuffer(data);
  29136. }
  29137. }
  29138. else if (this._updatable) { // update buffer
  29139. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29140. this._data = data;
  29141. }
  29142. };
  29143. Buffer.prototype._rebuild = function () {
  29144. this._buffer = null;
  29145. this.create(this._data);
  29146. };
  29147. Buffer.prototype.update = function (data) {
  29148. this.create(data);
  29149. };
  29150. /**
  29151. * Updates the data directly.
  29152. * @param data the new data
  29153. * @param offset the new offset
  29154. * @param vertexCount the vertex count (optional)
  29155. * @param useBytes set to true if the offset is in bytes
  29156. */
  29157. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29158. if (useBytes === void 0) { useBytes = false; }
  29159. if (!this._buffer) {
  29160. return;
  29161. }
  29162. if (this._updatable) { // update buffer
  29163. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29164. this._data = null;
  29165. }
  29166. };
  29167. Buffer.prototype.dispose = function () {
  29168. if (!this._buffer) {
  29169. return;
  29170. }
  29171. if (this._engine._releaseBuffer(this._buffer)) {
  29172. this._buffer = null;
  29173. }
  29174. };
  29175. return Buffer;
  29176. }());
  29177. BABYLON.Buffer = Buffer;
  29178. })(BABYLON || (BABYLON = {}));
  29179. //# sourceMappingURL=babylon.buffer.js.map
  29180. var BABYLON;
  29181. (function (BABYLON) {
  29182. var VertexBuffer = /** @class */ (function () {
  29183. /**
  29184. * Constructor
  29185. * @param engine the engine
  29186. * @param data the data to use for this vertex buffer
  29187. * @param kind the vertex buffer kind
  29188. * @param updatable whether the data is updatable
  29189. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29190. * @param stride the stride (optional)
  29191. * @param instanced whether the buffer is instanced (optional)
  29192. * @param offset the offset of the data (optional)
  29193. * @param size the number of components (optional)
  29194. * @param type the type of the component (optional)
  29195. * @param normalized whether the data contains normalized data (optional)
  29196. * @param useBytes set to true if stride and offset are in bytes (optional)
  29197. */
  29198. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29199. if (normalized === void 0) { normalized = false; }
  29200. if (useBytes === void 0) { useBytes = false; }
  29201. if (data instanceof BABYLON.Buffer) {
  29202. this._buffer = data;
  29203. this._ownsBuffer = false;
  29204. }
  29205. else {
  29206. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29207. this._ownsBuffer = true;
  29208. }
  29209. this._kind = kind;
  29210. if (type == undefined) {
  29211. var data_1 = this.getData();
  29212. this.type = VertexBuffer.FLOAT;
  29213. if (data_1 instanceof Int8Array)
  29214. this.type = VertexBuffer.BYTE;
  29215. else if (data_1 instanceof Uint8Array)
  29216. this.type = VertexBuffer.UNSIGNED_BYTE;
  29217. else if (data_1 instanceof Int16Array)
  29218. this.type = VertexBuffer.SHORT;
  29219. else if (data_1 instanceof Uint16Array)
  29220. this.type = VertexBuffer.UNSIGNED_SHORT;
  29221. else if (data_1 instanceof Int32Array)
  29222. this.type = VertexBuffer.INT;
  29223. else if (data_1 instanceof Uint32Array)
  29224. this.type = VertexBuffer.UNSIGNED_INT;
  29225. }
  29226. else {
  29227. this.type = type;
  29228. }
  29229. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29230. if (useBytes) {
  29231. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29232. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29233. this.byteOffset = offset || 0;
  29234. }
  29235. else {
  29236. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29237. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29238. this.byteOffset = (offset || 0) * typeByteLength;
  29239. }
  29240. this.normalized = normalized;
  29241. this._instanced = instanced !== undefined ? instanced : false;
  29242. this._instanceDivisor = instanced ? 1 : 0;
  29243. }
  29244. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29245. /**
  29246. * Gets or sets the instance divisor when in instanced mode
  29247. */
  29248. get: function () {
  29249. return this._instanceDivisor;
  29250. },
  29251. set: function (value) {
  29252. this._instanceDivisor = value;
  29253. if (value == 0) {
  29254. this._instanced = false;
  29255. }
  29256. else {
  29257. this._instanced = true;
  29258. }
  29259. },
  29260. enumerable: true,
  29261. configurable: true
  29262. });
  29263. VertexBuffer.prototype._rebuild = function () {
  29264. if (!this._buffer) {
  29265. return;
  29266. }
  29267. this._buffer._rebuild();
  29268. };
  29269. /**
  29270. * Returns the kind of the VertexBuffer (string).
  29271. */
  29272. VertexBuffer.prototype.getKind = function () {
  29273. return this._kind;
  29274. };
  29275. // Properties
  29276. /**
  29277. * Boolean : is the VertexBuffer updatable ?
  29278. */
  29279. VertexBuffer.prototype.isUpdatable = function () {
  29280. return this._buffer.isUpdatable();
  29281. };
  29282. /**
  29283. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29284. */
  29285. VertexBuffer.prototype.getData = function () {
  29286. return this._buffer.getData();
  29287. };
  29288. /**
  29289. * Returns the WebGLBuffer associated to the VertexBuffer.
  29290. */
  29291. VertexBuffer.prototype.getBuffer = function () {
  29292. return this._buffer.getBuffer();
  29293. };
  29294. /**
  29295. * Returns the stride as a multiple of the type byte length.
  29296. * DEPRECATED. Use byteStride instead.
  29297. */
  29298. VertexBuffer.prototype.getStrideSize = function () {
  29299. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29300. };
  29301. /**
  29302. * Returns the offset as a multiple of the type byte length.
  29303. * DEPRECATED. Use byteOffset instead.
  29304. */
  29305. VertexBuffer.prototype.getOffset = function () {
  29306. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29307. };
  29308. /**
  29309. * Returns the number of components per vertex attribute (integer).
  29310. */
  29311. VertexBuffer.prototype.getSize = function () {
  29312. return this._size;
  29313. };
  29314. /**
  29315. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29316. */
  29317. VertexBuffer.prototype.getIsInstanced = function () {
  29318. return this._instanced;
  29319. };
  29320. /**
  29321. * Returns the instancing divisor, zero for non-instanced (integer).
  29322. */
  29323. VertexBuffer.prototype.getInstanceDivisor = function () {
  29324. return this._instanceDivisor;
  29325. };
  29326. // Methods
  29327. /**
  29328. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29329. * Returns the created WebGLBuffer.
  29330. */
  29331. VertexBuffer.prototype.create = function (data) {
  29332. return this._buffer.create(data);
  29333. };
  29334. /**
  29335. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29336. * This function will create a new buffer if the current one is not updatable
  29337. * Returns the updated WebGLBuffer.
  29338. */
  29339. VertexBuffer.prototype.update = function (data) {
  29340. return this._buffer.update(data);
  29341. };
  29342. /**
  29343. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29344. * Returns the directly updated WebGLBuffer.
  29345. * @param data the new data
  29346. * @param offset the new offset
  29347. * @param useBytes set to true if the offset is in bytes
  29348. */
  29349. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29350. if (useBytes === void 0) { useBytes = false; }
  29351. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29352. };
  29353. /**
  29354. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29355. */
  29356. VertexBuffer.prototype.dispose = function () {
  29357. if (this._ownsBuffer) {
  29358. this._buffer.dispose();
  29359. }
  29360. };
  29361. /**
  29362. * Enumerates each value of this vertex buffer as numbers.
  29363. * @param count the number of values to enumerate
  29364. * @param callback the callback function called for each value
  29365. */
  29366. VertexBuffer.prototype.forEach = function (count, callback) {
  29367. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29368. };
  29369. Object.defineProperty(VertexBuffer, "PositionKind", {
  29370. get: function () {
  29371. return VertexBuffer._PositionKind;
  29372. },
  29373. enumerable: true,
  29374. configurable: true
  29375. });
  29376. Object.defineProperty(VertexBuffer, "NormalKind", {
  29377. get: function () {
  29378. return VertexBuffer._NormalKind;
  29379. },
  29380. enumerable: true,
  29381. configurable: true
  29382. });
  29383. Object.defineProperty(VertexBuffer, "TangentKind", {
  29384. get: function () {
  29385. return VertexBuffer._TangentKind;
  29386. },
  29387. enumerable: true,
  29388. configurable: true
  29389. });
  29390. Object.defineProperty(VertexBuffer, "UVKind", {
  29391. get: function () {
  29392. return VertexBuffer._UVKind;
  29393. },
  29394. enumerable: true,
  29395. configurable: true
  29396. });
  29397. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29398. get: function () {
  29399. return VertexBuffer._UV2Kind;
  29400. },
  29401. enumerable: true,
  29402. configurable: true
  29403. });
  29404. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29405. get: function () {
  29406. return VertexBuffer._UV3Kind;
  29407. },
  29408. enumerable: true,
  29409. configurable: true
  29410. });
  29411. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29412. get: function () {
  29413. return VertexBuffer._UV4Kind;
  29414. },
  29415. enumerable: true,
  29416. configurable: true
  29417. });
  29418. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29419. get: function () {
  29420. return VertexBuffer._UV5Kind;
  29421. },
  29422. enumerable: true,
  29423. configurable: true
  29424. });
  29425. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29426. get: function () {
  29427. return VertexBuffer._UV6Kind;
  29428. },
  29429. enumerable: true,
  29430. configurable: true
  29431. });
  29432. Object.defineProperty(VertexBuffer, "ColorKind", {
  29433. get: function () {
  29434. return VertexBuffer._ColorKind;
  29435. },
  29436. enumerable: true,
  29437. configurable: true
  29438. });
  29439. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29440. get: function () {
  29441. return VertexBuffer._MatricesIndicesKind;
  29442. },
  29443. enumerable: true,
  29444. configurable: true
  29445. });
  29446. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29447. get: function () {
  29448. return VertexBuffer._MatricesWeightsKind;
  29449. },
  29450. enumerable: true,
  29451. configurable: true
  29452. });
  29453. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29454. get: function () {
  29455. return VertexBuffer._MatricesIndicesExtraKind;
  29456. },
  29457. enumerable: true,
  29458. configurable: true
  29459. });
  29460. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29461. get: function () {
  29462. return VertexBuffer._MatricesWeightsExtraKind;
  29463. },
  29464. enumerable: true,
  29465. configurable: true
  29466. });
  29467. /**
  29468. * Deduces the stride given a kind.
  29469. * @param kind The kind string to deduce
  29470. * @returns The deduced stride
  29471. */
  29472. VertexBuffer.DeduceStride = function (kind) {
  29473. switch (kind) {
  29474. case VertexBuffer.UVKind:
  29475. case VertexBuffer.UV2Kind:
  29476. case VertexBuffer.UV3Kind:
  29477. case VertexBuffer.UV4Kind:
  29478. case VertexBuffer.UV5Kind:
  29479. case VertexBuffer.UV6Kind:
  29480. return 2;
  29481. case VertexBuffer.NormalKind:
  29482. case VertexBuffer.PositionKind:
  29483. return 3;
  29484. case VertexBuffer.ColorKind:
  29485. case VertexBuffer.MatricesIndicesKind:
  29486. case VertexBuffer.MatricesIndicesExtraKind:
  29487. case VertexBuffer.MatricesWeightsKind:
  29488. case VertexBuffer.MatricesWeightsExtraKind:
  29489. case VertexBuffer.TangentKind:
  29490. return 4;
  29491. default:
  29492. throw new Error("Invalid kind '" + kind + "'");
  29493. }
  29494. };
  29495. /**
  29496. * Gets the byte length of the given type.
  29497. * @param type the type
  29498. * @returns the number of bytes
  29499. */
  29500. VertexBuffer.GetTypeByteLength = function (type) {
  29501. switch (type) {
  29502. case VertexBuffer.BYTE:
  29503. case VertexBuffer.UNSIGNED_BYTE:
  29504. return 1;
  29505. case VertexBuffer.SHORT:
  29506. case VertexBuffer.UNSIGNED_SHORT:
  29507. return 2;
  29508. case VertexBuffer.INT:
  29509. case VertexBuffer.FLOAT:
  29510. return 4;
  29511. default:
  29512. throw new Error("Invalid type '" + type + "'");
  29513. }
  29514. };
  29515. /**
  29516. * Enumerates each value of the given parameters as numbers.
  29517. * @param data the data to enumerate
  29518. * @param byteOffset the byte offset of the data
  29519. * @param byteStride the byte stride of the data
  29520. * @param componentCount the number of components per element
  29521. * @param componentType the type of the component
  29522. * @param count the total number of components
  29523. * @param normalized whether the data is normalized
  29524. * @param callback the callback function called for each value
  29525. */
  29526. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29527. if (data instanceof Array) {
  29528. var offset = byteOffset / 4;
  29529. var stride = byteStride / 4;
  29530. for (var index = 0; index < count; index += componentCount) {
  29531. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29532. callback(data[offset + componentIndex], index + componentIndex);
  29533. }
  29534. offset += stride;
  29535. }
  29536. }
  29537. else {
  29538. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29539. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29540. for (var index = 0; index < count; index += componentCount) {
  29541. var componentByteOffset = byteOffset;
  29542. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29543. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29544. callback(value, index + componentIndex);
  29545. componentByteOffset += componentByteLength;
  29546. }
  29547. byteOffset += byteStride;
  29548. }
  29549. }
  29550. };
  29551. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29552. switch (type) {
  29553. case VertexBuffer.BYTE: {
  29554. var value = dataView.getInt8(byteOffset);
  29555. if (normalized) {
  29556. value = Math.max(value / 127, -1);
  29557. }
  29558. return value;
  29559. }
  29560. case VertexBuffer.UNSIGNED_BYTE: {
  29561. var value = dataView.getUint8(byteOffset);
  29562. if (normalized) {
  29563. value = value / 255;
  29564. }
  29565. return value;
  29566. }
  29567. case VertexBuffer.SHORT: {
  29568. var value = dataView.getInt16(byteOffset, true);
  29569. if (normalized) {
  29570. value = Math.max(value / 16383, -1);
  29571. }
  29572. return value;
  29573. }
  29574. case VertexBuffer.UNSIGNED_SHORT: {
  29575. var value = dataView.getUint16(byteOffset, true);
  29576. if (normalized) {
  29577. value = value / 65535;
  29578. }
  29579. return value;
  29580. }
  29581. case VertexBuffer.FLOAT: {
  29582. return dataView.getFloat32(byteOffset, true);
  29583. }
  29584. default: {
  29585. throw new Error("Invalid component type " + type);
  29586. }
  29587. }
  29588. };
  29589. /**
  29590. * The byte type.
  29591. */
  29592. VertexBuffer.BYTE = 5120;
  29593. /**
  29594. * The unsigned byte type.
  29595. */
  29596. VertexBuffer.UNSIGNED_BYTE = 5121;
  29597. /**
  29598. * The short type.
  29599. */
  29600. VertexBuffer.SHORT = 5122;
  29601. /**
  29602. * The unsigned short type.
  29603. */
  29604. VertexBuffer.UNSIGNED_SHORT = 5123;
  29605. /**
  29606. * The integer type.
  29607. */
  29608. VertexBuffer.INT = 5124;
  29609. /**
  29610. * The unsigned integer type.
  29611. */
  29612. VertexBuffer.UNSIGNED_INT = 5125;
  29613. /**
  29614. * The float type.
  29615. */
  29616. VertexBuffer.FLOAT = 5126;
  29617. // Enums
  29618. VertexBuffer._PositionKind = "position";
  29619. VertexBuffer._NormalKind = "normal";
  29620. VertexBuffer._TangentKind = "tangent";
  29621. VertexBuffer._UVKind = "uv";
  29622. VertexBuffer._UV2Kind = "uv2";
  29623. VertexBuffer._UV3Kind = "uv3";
  29624. VertexBuffer._UV4Kind = "uv4";
  29625. VertexBuffer._UV5Kind = "uv5";
  29626. VertexBuffer._UV6Kind = "uv6";
  29627. VertexBuffer._ColorKind = "color";
  29628. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29629. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29630. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29631. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29632. return VertexBuffer;
  29633. }());
  29634. BABYLON.VertexBuffer = VertexBuffer;
  29635. })(BABYLON || (BABYLON = {}));
  29636. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29637. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29638. var BABYLON;
  29639. (function (BABYLON) {
  29640. /**
  29641. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29642. */
  29643. var DummyInternalTextureTracker = /** @class */ (function () {
  29644. function DummyInternalTextureTracker() {
  29645. /**
  29646. * Gets or set the previous tracker in the list
  29647. */
  29648. this.previous = null;
  29649. /**
  29650. * Gets or set the next tracker in the list
  29651. */
  29652. this.next = null;
  29653. }
  29654. return DummyInternalTextureTracker;
  29655. }());
  29656. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29657. })(BABYLON || (BABYLON = {}));
  29658. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29659. var BABYLON;
  29660. (function (BABYLON) {
  29661. /**
  29662. * Class used to store data associated with WebGL texture data for the engine
  29663. * This class should not be used directly
  29664. */
  29665. var InternalTexture = /** @class */ (function () {
  29666. /**
  29667. * Creates a new InternalTexture
  29668. * @param engine defines the engine to use
  29669. * @param dataSource defines the type of data that will be used
  29670. */
  29671. function InternalTexture(engine, dataSource) {
  29672. /**
  29673. * Observable called when the texture is loaded
  29674. */
  29675. this.onLoadedObservable = new BABYLON.Observable();
  29676. /**
  29677. * Gets or set the previous tracker in the list
  29678. */
  29679. this.previous = null;
  29680. /**
  29681. * Gets or set the next tracker in the list
  29682. */
  29683. this.next = null;
  29684. // Private
  29685. /** @hidden */
  29686. this._initialSlot = -1;
  29687. /** @hidden */
  29688. this._designatedSlot = -1;
  29689. /** @hidden */
  29690. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29691. /** @hidden */
  29692. this._comparisonFunction = 0;
  29693. /** @hidden */
  29694. this._sphericalPolynomial = null;
  29695. /** @hidden */
  29696. this._lodGenerationScale = 0;
  29697. /** @hidden */
  29698. this._lodGenerationOffset = 0;
  29699. /** @hidden */
  29700. this._isRGBD = false;
  29701. /** @hidden */
  29702. this._references = 1;
  29703. this._engine = engine;
  29704. this._dataSource = dataSource;
  29705. this._webGLTexture = engine._createTexture();
  29706. }
  29707. /**
  29708. * Gets the Engine the texture belongs to.
  29709. * @returns The babylon engine
  29710. */
  29711. InternalTexture.prototype.getEngine = function () {
  29712. return this._engine;
  29713. };
  29714. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29715. /**
  29716. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29717. */
  29718. get: function () {
  29719. return this._dataSource;
  29720. },
  29721. enumerable: true,
  29722. configurable: true
  29723. });
  29724. /**
  29725. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29726. */
  29727. InternalTexture.prototype.incrementReferences = function () {
  29728. this._references++;
  29729. };
  29730. /**
  29731. * Change the size of the texture (not the size of the content)
  29732. * @param width defines the new width
  29733. * @param height defines the new height
  29734. * @param depth defines the new depth (1 by default)
  29735. */
  29736. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29737. if (depth === void 0) { depth = 1; }
  29738. this.width = width;
  29739. this.height = height;
  29740. this.depth = depth;
  29741. this.baseWidth = width;
  29742. this.baseHeight = height;
  29743. this.baseDepth = depth;
  29744. this._size = width * height * depth;
  29745. };
  29746. /** @hidden */
  29747. InternalTexture.prototype._rebuild = function () {
  29748. var _this = this;
  29749. var proxy;
  29750. this.isReady = false;
  29751. this._cachedCoordinatesMode = null;
  29752. this._cachedWrapU = null;
  29753. this._cachedWrapV = null;
  29754. this._cachedAnisotropicFilteringLevel = null;
  29755. switch (this._dataSource) {
  29756. case InternalTexture.DATASOURCE_TEMP:
  29757. return;
  29758. case InternalTexture.DATASOURCE_URL:
  29759. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29760. _this.isReady = true;
  29761. }, null, this._buffer, undefined, this.format);
  29762. proxy._swapAndDie(this);
  29763. return;
  29764. case InternalTexture.DATASOURCE_RAW:
  29765. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29766. proxy._swapAndDie(this);
  29767. this.isReady = true;
  29768. return;
  29769. case InternalTexture.DATASOURCE_RAW3D:
  29770. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29771. proxy._swapAndDie(this);
  29772. this.isReady = true;
  29773. return;
  29774. case InternalTexture.DATASOURCE_DYNAMIC:
  29775. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29776. proxy._swapAndDie(this);
  29777. // The engine will make sure to update content so no need to flag it as isReady = true
  29778. return;
  29779. case InternalTexture.DATASOURCE_RENDERTARGET:
  29780. var options = new BABYLON.RenderTargetCreationOptions();
  29781. options.generateDepthBuffer = this._generateDepthBuffer;
  29782. options.generateMipMaps = this.generateMipMaps;
  29783. options.generateStencilBuffer = this._generateStencilBuffer;
  29784. options.samplingMode = this.samplingMode;
  29785. options.type = this.type;
  29786. if (this.isCube) {
  29787. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29788. }
  29789. else {
  29790. var size = {
  29791. width: this.width,
  29792. height: this.height
  29793. };
  29794. proxy = this._engine.createRenderTargetTexture(size, options);
  29795. }
  29796. proxy._swapAndDie(this);
  29797. this.isReady = true;
  29798. return;
  29799. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29800. var depthTextureOptions = {
  29801. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29802. comparisonFunction: this._comparisonFunction,
  29803. generateStencil: this._generateStencilBuffer,
  29804. isCube: this.isCube
  29805. };
  29806. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29807. proxy._swapAndDie(this);
  29808. this.isReady = true;
  29809. return;
  29810. case InternalTexture.DATASOURCE_CUBE:
  29811. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29812. _this.isReady = true;
  29813. }, null, this.format, this._extension);
  29814. proxy._swapAndDie(this);
  29815. return;
  29816. case InternalTexture.DATASOURCE_CUBERAW:
  29817. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29818. proxy._swapAndDie(this);
  29819. this.isReady = true;
  29820. return;
  29821. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29822. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29823. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29824. _this.isReady = true;
  29825. });
  29826. proxy._swapAndDie(this);
  29827. return;
  29828. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29829. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29830. if (proxy) {
  29831. proxy._swapAndDie(_this);
  29832. }
  29833. _this.isReady = true;
  29834. }, null, this.format, this._extension);
  29835. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29836. return;
  29837. }
  29838. };
  29839. InternalTexture.prototype._swapAndDie = function (target) {
  29840. target._webGLTexture = this._webGLTexture;
  29841. if (this._framebuffer) {
  29842. target._framebuffer = this._framebuffer;
  29843. }
  29844. if (this._depthStencilBuffer) {
  29845. target._depthStencilBuffer = this._depthStencilBuffer;
  29846. }
  29847. if (this._lodTextureHigh) {
  29848. if (target._lodTextureHigh) {
  29849. target._lodTextureHigh.dispose();
  29850. }
  29851. target._lodTextureHigh = this._lodTextureHigh;
  29852. }
  29853. if (this._lodTextureMid) {
  29854. if (target._lodTextureMid) {
  29855. target._lodTextureMid.dispose();
  29856. }
  29857. target._lodTextureMid = this._lodTextureMid;
  29858. }
  29859. if (this._lodTextureLow) {
  29860. if (target._lodTextureLow) {
  29861. target._lodTextureLow.dispose();
  29862. }
  29863. target._lodTextureLow = this._lodTextureLow;
  29864. }
  29865. var cache = this._engine.getLoadedTexturesCache();
  29866. var index = cache.indexOf(this);
  29867. if (index !== -1) {
  29868. cache.splice(index, 1);
  29869. }
  29870. };
  29871. /**
  29872. * Dispose the current allocated resources
  29873. */
  29874. InternalTexture.prototype.dispose = function () {
  29875. if (!this._webGLTexture) {
  29876. return;
  29877. }
  29878. this._references--;
  29879. if (this._references === 0) {
  29880. this._engine._releaseTexture(this);
  29881. this._webGLTexture = null;
  29882. this.previous = null;
  29883. this.next = null;
  29884. }
  29885. };
  29886. /**
  29887. * The source of the texture data is unknown
  29888. */
  29889. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29890. /**
  29891. * Texture data comes from an URL
  29892. */
  29893. InternalTexture.DATASOURCE_URL = 1;
  29894. /**
  29895. * Texture data is only used for temporary storage
  29896. */
  29897. InternalTexture.DATASOURCE_TEMP = 2;
  29898. /**
  29899. * Texture data comes from raw data (ArrayBuffer)
  29900. */
  29901. InternalTexture.DATASOURCE_RAW = 3;
  29902. /**
  29903. * Texture content is dynamic (video or dynamic texture)
  29904. */
  29905. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29906. /**
  29907. * Texture content is generated by rendering to it
  29908. */
  29909. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29910. /**
  29911. * Texture content is part of a multi render target process
  29912. */
  29913. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29914. /**
  29915. * Texture data comes from a cube data file
  29916. */
  29917. InternalTexture.DATASOURCE_CUBE = 7;
  29918. /**
  29919. * Texture data comes from a raw cube data
  29920. */
  29921. InternalTexture.DATASOURCE_CUBERAW = 8;
  29922. /**
  29923. * Texture data come from a prefiltered cube data file
  29924. */
  29925. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29926. /**
  29927. * Texture content is raw 3D data
  29928. */
  29929. InternalTexture.DATASOURCE_RAW3D = 10;
  29930. /**
  29931. * Texture content is a depth texture
  29932. */
  29933. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29934. /**
  29935. * Texture data comes from a raw cube data encoded with RGBD
  29936. */
  29937. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29938. return InternalTexture;
  29939. }());
  29940. BABYLON.InternalTexture = InternalTexture;
  29941. })(BABYLON || (BABYLON = {}));
  29942. //# sourceMappingURL=babylon.internalTexture.js.map
  29943. var BABYLON;
  29944. (function (BABYLON) {
  29945. var BaseTexture = /** @class */ (function () {
  29946. function BaseTexture(scene) {
  29947. this._hasAlpha = false;
  29948. this.getAlphaFromRGB = false;
  29949. this.level = 1;
  29950. this.coordinatesIndex = 0;
  29951. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29952. /**
  29953. * | Value | Type | Description |
  29954. * | ----- | ------------------ | ----------- |
  29955. * | 0 | CLAMP_ADDRESSMODE | |
  29956. * | 1 | WRAP_ADDRESSMODE | |
  29957. * | 2 | MIRROR_ADDRESSMODE | |
  29958. */
  29959. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29960. /**
  29961. * | Value | Type | Description |
  29962. * | ----- | ------------------ | ----------- |
  29963. * | 0 | CLAMP_ADDRESSMODE | |
  29964. * | 1 | WRAP_ADDRESSMODE | |
  29965. * | 2 | MIRROR_ADDRESSMODE | |
  29966. */
  29967. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29968. /**
  29969. * | Value | Type | Description |
  29970. * | ----- | ------------------ | ----------- |
  29971. * | 0 | CLAMP_ADDRESSMODE | |
  29972. * | 1 | WRAP_ADDRESSMODE | |
  29973. * | 2 | MIRROR_ADDRESSMODE | |
  29974. */
  29975. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29976. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29977. this.isCube = false;
  29978. this.is3D = false;
  29979. this.gammaSpace = true;
  29980. this.invertZ = false;
  29981. this.lodLevelInAlpha = false;
  29982. this.isRenderTarget = false;
  29983. this.animations = new Array();
  29984. /**
  29985. * An event triggered when the texture is disposed.
  29986. */
  29987. this.onDisposeObservable = new BABYLON.Observable();
  29988. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29989. this._cachedSize = BABYLON.Size.Zero();
  29990. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29991. if (this._scene) {
  29992. this._scene.textures.push(this);
  29993. }
  29994. this._uid = null;
  29995. }
  29996. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29997. get: function () {
  29998. return this._hasAlpha;
  29999. },
  30000. set: function (value) {
  30001. if (this._hasAlpha === value) {
  30002. return;
  30003. }
  30004. this._hasAlpha = value;
  30005. if (this._scene) {
  30006. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30007. }
  30008. },
  30009. enumerable: true,
  30010. configurable: true
  30011. });
  30012. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30013. get: function () {
  30014. return this._coordinatesMode;
  30015. },
  30016. /**
  30017. * How a texture is mapped.
  30018. *
  30019. * | Value | Type | Description |
  30020. * | ----- | ----------------------------------- | ----------- |
  30021. * | 0 | EXPLICIT_MODE | |
  30022. * | 1 | SPHERICAL_MODE | |
  30023. * | 2 | PLANAR_MODE | |
  30024. * | 3 | CUBIC_MODE | |
  30025. * | 4 | PROJECTION_MODE | |
  30026. * | 5 | SKYBOX_MODE | |
  30027. * | 6 | INVCUBIC_MODE | |
  30028. * | 7 | EQUIRECTANGULAR_MODE | |
  30029. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30030. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30031. */
  30032. set: function (value) {
  30033. if (this._coordinatesMode === value) {
  30034. return;
  30035. }
  30036. this._coordinatesMode = value;
  30037. if (this._scene) {
  30038. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30039. }
  30040. },
  30041. enumerable: true,
  30042. configurable: true
  30043. });
  30044. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30045. /**
  30046. * Gets whether or not the texture contains RGBD data.
  30047. */
  30048. get: function () {
  30049. return this._texture != null && this._texture._isRGBD;
  30050. },
  30051. enumerable: true,
  30052. configurable: true
  30053. });
  30054. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30055. get: function () {
  30056. if (this._texture)
  30057. return this._texture._lodGenerationOffset;
  30058. return 0.0;
  30059. },
  30060. set: function (value) {
  30061. if (this._texture)
  30062. this._texture._lodGenerationOffset = value;
  30063. },
  30064. enumerable: true,
  30065. configurable: true
  30066. });
  30067. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30068. get: function () {
  30069. if (this._texture)
  30070. return this._texture._lodGenerationScale;
  30071. return 0.0;
  30072. },
  30073. set: function (value) {
  30074. if (this._texture)
  30075. this._texture._lodGenerationScale = value;
  30076. },
  30077. enumerable: true,
  30078. configurable: true
  30079. });
  30080. Object.defineProperty(BaseTexture.prototype, "uid", {
  30081. get: function () {
  30082. if (!this._uid) {
  30083. this._uid = BABYLON.Tools.RandomId();
  30084. }
  30085. return this._uid;
  30086. },
  30087. enumerable: true,
  30088. configurable: true
  30089. });
  30090. BaseTexture.prototype.toString = function () {
  30091. return this.name;
  30092. };
  30093. BaseTexture.prototype.getClassName = function () {
  30094. return "BaseTexture";
  30095. };
  30096. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30097. set: function (callback) {
  30098. if (this._onDisposeObserver) {
  30099. this.onDisposeObservable.remove(this._onDisposeObserver);
  30100. }
  30101. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30102. },
  30103. enumerable: true,
  30104. configurable: true
  30105. });
  30106. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30107. get: function () {
  30108. return true;
  30109. },
  30110. enumerable: true,
  30111. configurable: true
  30112. });
  30113. BaseTexture.prototype.getScene = function () {
  30114. return this._scene;
  30115. };
  30116. BaseTexture.prototype.getTextureMatrix = function () {
  30117. return BABYLON.Matrix.IdentityReadOnly;
  30118. };
  30119. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30120. return BABYLON.Matrix.IdentityReadOnly;
  30121. };
  30122. BaseTexture.prototype.getInternalTexture = function () {
  30123. return this._texture;
  30124. };
  30125. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30126. return !this.isBlocking || this.isReady();
  30127. };
  30128. BaseTexture.prototype.isReady = function () {
  30129. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30130. this.delayLoad();
  30131. return false;
  30132. }
  30133. if (this._texture) {
  30134. return this._texture.isReady;
  30135. }
  30136. return false;
  30137. };
  30138. BaseTexture.prototype.getSize = function () {
  30139. if (this._texture) {
  30140. if (this._texture.width) {
  30141. this._cachedSize.width = this._texture.width;
  30142. this._cachedSize.height = this._texture.height;
  30143. return this._cachedSize;
  30144. }
  30145. if (this._texture._size) {
  30146. this._cachedSize.width = this._texture._size;
  30147. this._cachedSize.height = this._texture._size;
  30148. return this._cachedSize;
  30149. }
  30150. }
  30151. return this._cachedSize;
  30152. };
  30153. BaseTexture.prototype.getBaseSize = function () {
  30154. if (!this.isReady() || !this._texture)
  30155. return BABYLON.Size.Zero();
  30156. if (this._texture._size) {
  30157. return new BABYLON.Size(this._texture._size, this._texture._size);
  30158. }
  30159. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30160. };
  30161. BaseTexture.prototype.scale = function (ratio) {
  30162. };
  30163. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30164. get: function () {
  30165. return false;
  30166. },
  30167. enumerable: true,
  30168. configurable: true
  30169. });
  30170. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30171. if (!this._scene) {
  30172. return null;
  30173. }
  30174. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30175. for (var index = 0; index < texturesCache.length; index++) {
  30176. var texturesCacheEntry = texturesCache[index];
  30177. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30178. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30179. texturesCacheEntry.incrementReferences();
  30180. return texturesCacheEntry;
  30181. }
  30182. }
  30183. }
  30184. return null;
  30185. };
  30186. BaseTexture.prototype._rebuild = function () {
  30187. };
  30188. BaseTexture.prototype.delayLoad = function () {
  30189. };
  30190. BaseTexture.prototype.clone = function () {
  30191. return null;
  30192. };
  30193. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30194. get: function () {
  30195. if (!this._texture) {
  30196. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30197. }
  30198. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30199. },
  30200. enumerable: true,
  30201. configurable: true
  30202. });
  30203. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30204. get: function () {
  30205. if (!this._texture) {
  30206. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30207. }
  30208. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30209. },
  30210. enumerable: true,
  30211. configurable: true
  30212. });
  30213. /**
  30214. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30215. * This will returns an RGBA array buffer containing either in values (0-255) or
  30216. * float values (0-1) depending of the underlying buffer type.
  30217. * @param faceIndex The face of the texture to read (in case of cube texture)
  30218. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30219. * @returns The Array buffer containing the pixels data.
  30220. */
  30221. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30222. if (faceIndex === void 0) { faceIndex = 0; }
  30223. if (level === void 0) { level = 0; }
  30224. if (!this._texture) {
  30225. return null;
  30226. }
  30227. var size = this.getSize();
  30228. var width = size.width;
  30229. var height = size.height;
  30230. var scene = this.getScene();
  30231. if (!scene) {
  30232. return null;
  30233. }
  30234. var engine = scene.getEngine();
  30235. if (level != 0) {
  30236. width = width / Math.pow(2, level);
  30237. height = height / Math.pow(2, level);
  30238. width = Math.round(width);
  30239. height = Math.round(height);
  30240. }
  30241. if (this._texture.isCube) {
  30242. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30243. }
  30244. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30245. };
  30246. BaseTexture.prototype.releaseInternalTexture = function () {
  30247. if (this._texture) {
  30248. this._texture.dispose();
  30249. this._texture = null;
  30250. }
  30251. };
  30252. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30253. get: function () {
  30254. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30255. return null;
  30256. }
  30257. if (!this._texture._sphericalPolynomial) {
  30258. this._texture._sphericalPolynomial =
  30259. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30260. }
  30261. return this._texture._sphericalPolynomial;
  30262. },
  30263. set: function (value) {
  30264. if (this._texture) {
  30265. this._texture._sphericalPolynomial = value;
  30266. }
  30267. },
  30268. enumerable: true,
  30269. configurable: true
  30270. });
  30271. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30272. get: function () {
  30273. if (this._texture) {
  30274. return this._texture._lodTextureHigh;
  30275. }
  30276. return null;
  30277. },
  30278. enumerable: true,
  30279. configurable: true
  30280. });
  30281. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30282. get: function () {
  30283. if (this._texture) {
  30284. return this._texture._lodTextureMid;
  30285. }
  30286. return null;
  30287. },
  30288. enumerable: true,
  30289. configurable: true
  30290. });
  30291. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30292. get: function () {
  30293. if (this._texture) {
  30294. return this._texture._lodTextureLow;
  30295. }
  30296. return null;
  30297. },
  30298. enumerable: true,
  30299. configurable: true
  30300. });
  30301. BaseTexture.prototype.dispose = function () {
  30302. if (!this._scene) {
  30303. return;
  30304. }
  30305. // Animations
  30306. this._scene.stopAnimation(this);
  30307. // Remove from scene
  30308. this._scene._removePendingData(this);
  30309. var index = this._scene.textures.indexOf(this);
  30310. if (index >= 0) {
  30311. this._scene.textures.splice(index, 1);
  30312. }
  30313. if (this._texture === undefined) {
  30314. return;
  30315. }
  30316. // Release
  30317. this.releaseInternalTexture();
  30318. // Callback
  30319. this.onDisposeObservable.notifyObservers(this);
  30320. this.onDisposeObservable.clear();
  30321. };
  30322. BaseTexture.prototype.serialize = function () {
  30323. if (!this.name) {
  30324. return null;
  30325. }
  30326. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30327. // Animations
  30328. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30329. return serializationObject;
  30330. };
  30331. BaseTexture.WhenAllReady = function (textures, callback) {
  30332. var numRemaining = textures.length;
  30333. if (numRemaining === 0) {
  30334. callback();
  30335. return;
  30336. }
  30337. var _loop_1 = function () {
  30338. texture = textures[i];
  30339. if (texture.isReady()) {
  30340. if (--numRemaining === 0) {
  30341. callback();
  30342. }
  30343. }
  30344. else {
  30345. onLoadObservable = texture.onLoadObservable;
  30346. var onLoadCallback_1 = function () {
  30347. onLoadObservable.removeCallback(onLoadCallback_1);
  30348. if (--numRemaining === 0) {
  30349. callback();
  30350. }
  30351. };
  30352. onLoadObservable.add(onLoadCallback_1);
  30353. }
  30354. };
  30355. var texture, onLoadObservable;
  30356. for (var i = 0; i < textures.length; i++) {
  30357. _loop_1();
  30358. }
  30359. };
  30360. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30361. __decorate([
  30362. BABYLON.serialize()
  30363. ], BaseTexture.prototype, "name", void 0);
  30364. __decorate([
  30365. BABYLON.serialize("hasAlpha")
  30366. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30367. __decorate([
  30368. BABYLON.serialize()
  30369. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30370. __decorate([
  30371. BABYLON.serialize()
  30372. ], BaseTexture.prototype, "level", void 0);
  30373. __decorate([
  30374. BABYLON.serialize()
  30375. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30376. __decorate([
  30377. BABYLON.serialize("coordinatesMode")
  30378. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30379. __decorate([
  30380. BABYLON.serialize()
  30381. ], BaseTexture.prototype, "wrapU", void 0);
  30382. __decorate([
  30383. BABYLON.serialize()
  30384. ], BaseTexture.prototype, "wrapV", void 0);
  30385. __decorate([
  30386. BABYLON.serialize()
  30387. ], BaseTexture.prototype, "wrapR", void 0);
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30391. __decorate([
  30392. BABYLON.serialize()
  30393. ], BaseTexture.prototype, "isCube", void 0);
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], BaseTexture.prototype, "is3D", void 0);
  30397. __decorate([
  30398. BABYLON.serialize()
  30399. ], BaseTexture.prototype, "gammaSpace", void 0);
  30400. __decorate([
  30401. BABYLON.serialize()
  30402. ], BaseTexture.prototype, "invertZ", void 0);
  30403. __decorate([
  30404. BABYLON.serialize()
  30405. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30406. __decorate([
  30407. BABYLON.serialize()
  30408. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30409. __decorate([
  30410. BABYLON.serialize()
  30411. ], BaseTexture.prototype, "lodGenerationScale", null);
  30412. __decorate([
  30413. BABYLON.serialize()
  30414. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30415. return BaseTexture;
  30416. }());
  30417. BABYLON.BaseTexture = BaseTexture;
  30418. })(BABYLON || (BABYLON = {}));
  30419. //# sourceMappingURL=babylon.baseTexture.js.map
  30420. var BABYLON;
  30421. (function (BABYLON) {
  30422. var Texture = /** @class */ (function (_super) {
  30423. __extends(Texture, _super);
  30424. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30425. if (noMipmap === void 0) { noMipmap = false; }
  30426. if (invertY === void 0) { invertY = true; }
  30427. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30428. if (onLoad === void 0) { onLoad = null; }
  30429. if (onError === void 0) { onError = null; }
  30430. if (buffer === void 0) { buffer = null; }
  30431. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30432. var _this = _super.call(this, scene) || this;
  30433. _this.uOffset = 0;
  30434. _this.vOffset = 0;
  30435. _this.uScale = 1.0;
  30436. _this.vScale = 1.0;
  30437. _this.uAng = 0;
  30438. _this.vAng = 0;
  30439. _this.wAng = 0;
  30440. /**
  30441. * Defines the center of rotation (U)
  30442. */
  30443. _this.uRotationCenter = 0.5;
  30444. /**
  30445. * Defines the center of rotation (V)
  30446. */
  30447. _this.vRotationCenter = 0.5;
  30448. /**
  30449. * Defines the center of rotation (W)
  30450. */
  30451. _this.wRotationCenter = 0.5;
  30452. _this._isBlocking = true;
  30453. _this.name = url || "";
  30454. _this.url = url;
  30455. _this._noMipmap = noMipmap;
  30456. _this._invertY = invertY;
  30457. _this._samplingMode = samplingMode;
  30458. _this._buffer = buffer;
  30459. _this._deleteBuffer = deleteBuffer;
  30460. if (format) {
  30461. _this._format = format;
  30462. }
  30463. scene = _this.getScene();
  30464. if (!scene) {
  30465. return _this;
  30466. }
  30467. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30468. var load = function () {
  30469. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30470. _this.onLoadObservable.notifyObservers(_this);
  30471. }
  30472. if (onLoad) {
  30473. onLoad();
  30474. }
  30475. if (!_this.isBlocking && scene) {
  30476. scene.resetCachedMaterial();
  30477. }
  30478. };
  30479. if (!_this.url) {
  30480. _this._delayedOnLoad = load;
  30481. _this._delayedOnError = onError;
  30482. return _this;
  30483. }
  30484. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30485. if (!_this._texture) {
  30486. if (!scene.useDelayedTextureLoading) {
  30487. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30488. if (deleteBuffer) {
  30489. delete _this._buffer;
  30490. }
  30491. }
  30492. else {
  30493. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30494. _this._delayedOnLoad = load;
  30495. _this._delayedOnError = onError;
  30496. }
  30497. }
  30498. else {
  30499. if (_this._texture.isReady) {
  30500. BABYLON.Tools.SetImmediate(function () { return load(); });
  30501. }
  30502. else {
  30503. _this._texture.onLoadedObservable.add(load);
  30504. }
  30505. }
  30506. return _this;
  30507. }
  30508. Object.defineProperty(Texture.prototype, "noMipmap", {
  30509. get: function () {
  30510. return this._noMipmap;
  30511. },
  30512. enumerable: true,
  30513. configurable: true
  30514. });
  30515. Object.defineProperty(Texture.prototype, "isBlocking", {
  30516. get: function () {
  30517. return this._isBlocking;
  30518. },
  30519. set: function (value) {
  30520. this._isBlocking = value;
  30521. },
  30522. enumerable: true,
  30523. configurable: true
  30524. });
  30525. Object.defineProperty(Texture.prototype, "samplingMode", {
  30526. get: function () {
  30527. return this._samplingMode;
  30528. },
  30529. enumerable: true,
  30530. configurable: true
  30531. });
  30532. /**
  30533. * Update the url (and optional buffer) of this texture if url was null during construction.
  30534. * @param url the url of the texture
  30535. * @param buffer the buffer of the texture (defaults to null)
  30536. */
  30537. Texture.prototype.updateURL = function (url, buffer) {
  30538. if (buffer === void 0) { buffer = null; }
  30539. if (this.url) {
  30540. throw new Error("URL is already set");
  30541. }
  30542. this.url = url;
  30543. this._buffer = buffer;
  30544. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30545. this.delayLoad();
  30546. };
  30547. Texture.prototype.delayLoad = function () {
  30548. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30549. return;
  30550. }
  30551. var scene = this.getScene();
  30552. if (!scene) {
  30553. return;
  30554. }
  30555. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30556. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30557. if (!this._texture) {
  30558. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30559. if (this._deleteBuffer) {
  30560. delete this._buffer;
  30561. }
  30562. }
  30563. else {
  30564. if (this._delayedOnLoad) {
  30565. if (this._texture.isReady) {
  30566. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30567. }
  30568. else {
  30569. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30570. }
  30571. }
  30572. }
  30573. this._delayedOnLoad = null;
  30574. this._delayedOnError = null;
  30575. };
  30576. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30577. if (!this._texture) {
  30578. return;
  30579. }
  30580. var scene = this.getScene();
  30581. if (!scene) {
  30582. return;
  30583. }
  30584. this._samplingMode = samplingMode;
  30585. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30586. };
  30587. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30588. x *= this.uScale;
  30589. y *= this.vScale;
  30590. x -= this.uRotationCenter * this.uScale;
  30591. y -= this.vRotationCenter * this.vScale;
  30592. z -= this.wRotationCenter;
  30593. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30594. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30595. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30596. t.z += this.wRotationCenter;
  30597. };
  30598. Texture.prototype.getTextureMatrix = function () {
  30599. var _this = this;
  30600. if (this.uOffset === this._cachedUOffset &&
  30601. this.vOffset === this._cachedVOffset &&
  30602. this.uScale === this._cachedUScale &&
  30603. this.vScale === this._cachedVScale &&
  30604. this.uAng === this._cachedUAng &&
  30605. this.vAng === this._cachedVAng &&
  30606. this.wAng === this._cachedWAng) {
  30607. return this._cachedTextureMatrix;
  30608. }
  30609. this._cachedUOffset = this.uOffset;
  30610. this._cachedVOffset = this.vOffset;
  30611. this._cachedUScale = this.uScale;
  30612. this._cachedVScale = this.vScale;
  30613. this._cachedUAng = this.uAng;
  30614. this._cachedVAng = this.vAng;
  30615. this._cachedWAng = this.wAng;
  30616. if (!this._cachedTextureMatrix) {
  30617. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30618. this._rowGenerationMatrix = new BABYLON.Matrix();
  30619. this._t0 = BABYLON.Vector3.Zero();
  30620. this._t1 = BABYLON.Vector3.Zero();
  30621. this._t2 = BABYLON.Vector3.Zero();
  30622. }
  30623. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30624. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30625. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30626. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30627. this._t1.subtractInPlace(this._t0);
  30628. this._t2.subtractInPlace(this._t0);
  30629. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30630. this._cachedTextureMatrix.m[0] = this._t1.x;
  30631. this._cachedTextureMatrix.m[1] = this._t1.y;
  30632. this._cachedTextureMatrix.m[2] = this._t1.z;
  30633. this._cachedTextureMatrix.m[4] = this._t2.x;
  30634. this._cachedTextureMatrix.m[5] = this._t2.y;
  30635. this._cachedTextureMatrix.m[6] = this._t2.z;
  30636. this._cachedTextureMatrix.m[8] = this._t0.x;
  30637. this._cachedTextureMatrix.m[9] = this._t0.y;
  30638. this._cachedTextureMatrix.m[10] = this._t0.z;
  30639. var scene = this.getScene();
  30640. if (!scene) {
  30641. return this._cachedTextureMatrix;
  30642. }
  30643. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30644. return mat.hasTexture(_this);
  30645. });
  30646. return this._cachedTextureMatrix;
  30647. };
  30648. Texture.prototype.getReflectionTextureMatrix = function () {
  30649. var _this = this;
  30650. var scene = this.getScene();
  30651. if (!scene) {
  30652. return this._cachedTextureMatrix;
  30653. }
  30654. if (this.uOffset === this._cachedUOffset &&
  30655. this.vOffset === this._cachedVOffset &&
  30656. this.uScale === this._cachedUScale &&
  30657. this.vScale === this._cachedVScale &&
  30658. this.coordinatesMode === this._cachedCoordinatesMode) {
  30659. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30660. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30661. return this._cachedTextureMatrix;
  30662. }
  30663. }
  30664. else {
  30665. return this._cachedTextureMatrix;
  30666. }
  30667. }
  30668. if (!this._cachedTextureMatrix) {
  30669. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30670. }
  30671. if (!this._projectionModeMatrix) {
  30672. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30673. }
  30674. this._cachedUOffset = this.uOffset;
  30675. this._cachedVOffset = this.vOffset;
  30676. this._cachedUScale = this.uScale;
  30677. this._cachedVScale = this.vScale;
  30678. this._cachedCoordinatesMode = this.coordinatesMode;
  30679. switch (this.coordinatesMode) {
  30680. case Texture.PLANAR_MODE:
  30681. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30682. this._cachedTextureMatrix[0] = this.uScale;
  30683. this._cachedTextureMatrix[5] = this.vScale;
  30684. this._cachedTextureMatrix[12] = this.uOffset;
  30685. this._cachedTextureMatrix[13] = this.vOffset;
  30686. break;
  30687. case Texture.PROJECTION_MODE:
  30688. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30689. this._projectionModeMatrix.m[0] = 0.5;
  30690. this._projectionModeMatrix.m[5] = -0.5;
  30691. this._projectionModeMatrix.m[10] = 0.0;
  30692. this._projectionModeMatrix.m[12] = 0.5;
  30693. this._projectionModeMatrix.m[13] = 0.5;
  30694. this._projectionModeMatrix.m[14] = 1.0;
  30695. this._projectionModeMatrix.m[15] = 1.0;
  30696. var projectionMatrix = scene.getProjectionMatrix();
  30697. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30698. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30699. break;
  30700. default:
  30701. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30702. break;
  30703. }
  30704. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30705. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30706. });
  30707. return this._cachedTextureMatrix;
  30708. };
  30709. Texture.prototype.clone = function () {
  30710. var _this = this;
  30711. return BABYLON.SerializationHelper.Clone(function () {
  30712. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30713. }, this);
  30714. };
  30715. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30716. get: function () {
  30717. if (!this._onLoadObservable) {
  30718. this._onLoadObservable = new BABYLON.Observable();
  30719. }
  30720. return this._onLoadObservable;
  30721. },
  30722. enumerable: true,
  30723. configurable: true
  30724. });
  30725. Texture.prototype.serialize = function () {
  30726. var serializationObject = _super.prototype.serialize.call(this);
  30727. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30728. serializationObject.base64String = this._buffer;
  30729. serializationObject.name = serializationObject.name.replace("data:", "");
  30730. }
  30731. serializationObject.invertY = this._invertY;
  30732. serializationObject.samplingMode = this.samplingMode;
  30733. return serializationObject;
  30734. };
  30735. Texture.prototype.getClassName = function () {
  30736. return "Texture";
  30737. };
  30738. Texture.prototype.dispose = function () {
  30739. _super.prototype.dispose.call(this);
  30740. if (this._onLoadObservable) {
  30741. this._onLoadObservable.clear();
  30742. this._onLoadObservable = null;
  30743. }
  30744. this._delayedOnLoad = null;
  30745. this._delayedOnError = null;
  30746. };
  30747. // Statics
  30748. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30749. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30750. if (onLoad === void 0) { onLoad = null; }
  30751. if (onError === void 0) { onError = null; }
  30752. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30753. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30754. };
  30755. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30756. if (parsedTexture.customType) {
  30757. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30758. // Update Sampling Mode
  30759. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30760. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30761. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30762. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30763. }
  30764. }
  30765. return parsedCustomTexture;
  30766. }
  30767. if (parsedTexture.isCube) {
  30768. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30769. }
  30770. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30771. return null;
  30772. }
  30773. var texture = BABYLON.SerializationHelper.Parse(function () {
  30774. var generateMipMaps = true;
  30775. if (parsedTexture.noMipmap) {
  30776. generateMipMaps = false;
  30777. }
  30778. if (parsedTexture.mirrorPlane) {
  30779. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30780. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30781. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30782. return mirrorTexture;
  30783. }
  30784. else if (parsedTexture.isRenderTarget) {
  30785. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30786. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30787. return renderTargetTexture;
  30788. }
  30789. else {
  30790. var texture;
  30791. if (parsedTexture.base64String) {
  30792. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30793. }
  30794. else {
  30795. var url = rootUrl + parsedTexture.name;
  30796. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30797. url = parsedTexture.url;
  30798. }
  30799. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30800. }
  30801. return texture;
  30802. }
  30803. }, parsedTexture, scene);
  30804. // Update Sampling Mode
  30805. if (parsedTexture.samplingMode) {
  30806. var sampling = parsedTexture.samplingMode;
  30807. if (texture._samplingMode !== sampling) {
  30808. texture.updateSamplingMode(sampling);
  30809. }
  30810. }
  30811. // Animations
  30812. if (parsedTexture.animations) {
  30813. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30814. var parsedAnimation = parsedTexture.animations[animationIndex];
  30815. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30816. }
  30817. }
  30818. return texture;
  30819. };
  30820. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30821. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30822. if (noMipmap === void 0) { noMipmap = false; }
  30823. if (invertY === void 0) { invertY = true; }
  30824. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30825. if (onLoad === void 0) { onLoad = null; }
  30826. if (onError === void 0) { onError = null; }
  30827. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30828. if (name.substr(0, 5) !== "data:") {
  30829. name = "data:" + name;
  30830. }
  30831. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30832. };
  30833. // Constants
  30834. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30835. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30836. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30837. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30838. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30839. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30840. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30841. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30842. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30843. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30844. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30845. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30846. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30847. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30848. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30849. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30850. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30851. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30852. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30853. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30854. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30855. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30856. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30857. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30858. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30859. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30860. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30861. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30862. /**
  30863. * 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
  30864. */
  30865. Texture.UseSerializedUrlIfAny = false;
  30866. __decorate([
  30867. BABYLON.serialize()
  30868. ], Texture.prototype, "url", void 0);
  30869. __decorate([
  30870. BABYLON.serialize()
  30871. ], Texture.prototype, "uOffset", void 0);
  30872. __decorate([
  30873. BABYLON.serialize()
  30874. ], Texture.prototype, "vOffset", void 0);
  30875. __decorate([
  30876. BABYLON.serialize()
  30877. ], Texture.prototype, "uScale", void 0);
  30878. __decorate([
  30879. BABYLON.serialize()
  30880. ], Texture.prototype, "vScale", void 0);
  30881. __decorate([
  30882. BABYLON.serialize()
  30883. ], Texture.prototype, "uAng", void 0);
  30884. __decorate([
  30885. BABYLON.serialize()
  30886. ], Texture.prototype, "vAng", void 0);
  30887. __decorate([
  30888. BABYLON.serialize()
  30889. ], Texture.prototype, "wAng", void 0);
  30890. __decorate([
  30891. BABYLON.serialize()
  30892. ], Texture.prototype, "uRotationCenter", void 0);
  30893. __decorate([
  30894. BABYLON.serialize()
  30895. ], Texture.prototype, "vRotationCenter", void 0);
  30896. __decorate([
  30897. BABYLON.serialize()
  30898. ], Texture.prototype, "wRotationCenter", void 0);
  30899. __decorate([
  30900. BABYLON.serialize()
  30901. ], Texture.prototype, "isBlocking", null);
  30902. return Texture;
  30903. }(BABYLON.BaseTexture));
  30904. BABYLON.Texture = Texture;
  30905. })(BABYLON || (BABYLON = {}));
  30906. //# sourceMappingURL=babylon.texture.js.map
  30907. var BABYLON;
  30908. (function (BABYLON) {
  30909. /**
  30910. * @hidden
  30911. **/
  30912. var _InstancesBatch = /** @class */ (function () {
  30913. function _InstancesBatch() {
  30914. this.mustReturn = false;
  30915. this.visibleInstances = new Array();
  30916. this.renderSelf = new Array();
  30917. }
  30918. return _InstancesBatch;
  30919. }());
  30920. BABYLON._InstancesBatch = _InstancesBatch;
  30921. var Mesh = /** @class */ (function (_super) {
  30922. __extends(Mesh, _super);
  30923. /**
  30924. * @constructor
  30925. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30926. * @param {Scene} scene The scene to add this mesh to.
  30927. * @param {Node} parent The parent of this mesh, if it has one
  30928. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30929. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30930. * When false, achieved by calling a clone(), also passing False.
  30931. * This will make creation of children, recursive.
  30932. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30933. */
  30934. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30935. if (scene === void 0) { scene = null; }
  30936. if (parent === void 0) { parent = null; }
  30937. if (source === void 0) { source = null; }
  30938. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30939. var _this = _super.call(this, name, scene) || this;
  30940. // Members
  30941. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30942. _this.instances = new Array();
  30943. _this._LODLevels = new Array();
  30944. _this._visibleInstances = {};
  30945. _this._renderIdForInstances = new Array();
  30946. _this._batchCache = new _InstancesBatch();
  30947. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30948. // Use by builder only to know what orientation were the mesh build in.
  30949. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30950. _this.overrideMaterialSideOrientation = null;
  30951. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30952. // Will be used to save a source mesh reference, If any
  30953. _this._source = null;
  30954. scene = _this.getScene();
  30955. if (source) {
  30956. // Geometry
  30957. if (source._geometry) {
  30958. source._geometry.applyToMesh(_this);
  30959. }
  30960. // Deep copy
  30961. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30962. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30963. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30964. ], ["_poseMatrix"]);
  30965. // Source mesh
  30966. _this._source = source;
  30967. // Metadata
  30968. if (source.metadata && source.metadata.clone) {
  30969. _this.metadata = source.metadata.clone();
  30970. }
  30971. else {
  30972. _this.metadata = source.metadata;
  30973. }
  30974. // Tags
  30975. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30976. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30977. }
  30978. // Parent
  30979. _this.parent = source.parent;
  30980. // Pivot
  30981. _this.setPivotMatrix(source.getPivotMatrix());
  30982. _this.id = name + "." + source.id;
  30983. // Material
  30984. _this.material = source.material;
  30985. var index;
  30986. if (!doNotCloneChildren) {
  30987. // Children
  30988. var directDescendants = source.getDescendants(true);
  30989. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30990. var child = directDescendants[index_1];
  30991. if (child.clone) {
  30992. child.clone(name + "." + child.name, _this);
  30993. }
  30994. }
  30995. }
  30996. // Physics clone
  30997. var physicsEngine = _this.getScene().getPhysicsEngine();
  30998. if (clonePhysicsImpostor && physicsEngine) {
  30999. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31000. if (impostor) {
  31001. _this.physicsImpostor = impostor.clone(_this);
  31002. }
  31003. }
  31004. // Particles
  31005. for (index = 0; index < scene.particleSystems.length; index++) {
  31006. var system = scene.particleSystems[index];
  31007. if (system.emitter === source) {
  31008. system.clone(system.name, _this);
  31009. }
  31010. }
  31011. _this.refreshBoundingInfo();
  31012. _this.computeWorldMatrix(true);
  31013. }
  31014. // Parent
  31015. if (parent !== null) {
  31016. _this.parent = parent;
  31017. }
  31018. return _this;
  31019. }
  31020. Object.defineProperty(Mesh, "FRONTSIDE", {
  31021. /**
  31022. * Mesh side orientation : usually the external or front surface
  31023. */
  31024. get: function () {
  31025. return Mesh._FRONTSIDE;
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Mesh, "BACKSIDE", {
  31031. /**
  31032. * Mesh side orientation : usually the internal or back surface
  31033. */
  31034. get: function () {
  31035. return Mesh._BACKSIDE;
  31036. },
  31037. enumerable: true,
  31038. configurable: true
  31039. });
  31040. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31041. /**
  31042. * Mesh side orientation : both internal and external or front and back surfaces
  31043. */
  31044. get: function () {
  31045. return Mesh._DOUBLESIDE;
  31046. },
  31047. enumerable: true,
  31048. configurable: true
  31049. });
  31050. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31051. /**
  31052. * Mesh side orientation : by default, `FRONTSIDE`
  31053. */
  31054. get: function () {
  31055. return Mesh._DEFAULTSIDE;
  31056. },
  31057. enumerable: true,
  31058. configurable: true
  31059. });
  31060. Object.defineProperty(Mesh, "NO_CAP", {
  31061. /**
  31062. * Mesh cap setting : no cap
  31063. */
  31064. get: function () {
  31065. return Mesh._NO_CAP;
  31066. },
  31067. enumerable: true,
  31068. configurable: true
  31069. });
  31070. Object.defineProperty(Mesh, "CAP_START", {
  31071. /**
  31072. * Mesh cap setting : one cap at the beginning of the mesh
  31073. */
  31074. get: function () {
  31075. return Mesh._CAP_START;
  31076. },
  31077. enumerable: true,
  31078. configurable: true
  31079. });
  31080. Object.defineProperty(Mesh, "CAP_END", {
  31081. /**
  31082. * Mesh cap setting : one cap at the end of the mesh
  31083. */
  31084. get: function () {
  31085. return Mesh._CAP_END;
  31086. },
  31087. enumerable: true,
  31088. configurable: true
  31089. });
  31090. Object.defineProperty(Mesh, "CAP_ALL", {
  31091. /**
  31092. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31093. */
  31094. get: function () {
  31095. return Mesh._CAP_ALL;
  31096. },
  31097. enumerable: true,
  31098. configurable: true
  31099. });
  31100. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31101. /**
  31102. * An event triggered before rendering the mesh
  31103. */
  31104. get: function () {
  31105. if (!this._onBeforeRenderObservable) {
  31106. this._onBeforeRenderObservable = new BABYLON.Observable();
  31107. }
  31108. return this._onBeforeRenderObservable;
  31109. },
  31110. enumerable: true,
  31111. configurable: true
  31112. });
  31113. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31114. /**
  31115. * An event triggered after rendering the mesh
  31116. */
  31117. get: function () {
  31118. if (!this._onAfterRenderObservable) {
  31119. this._onAfterRenderObservable = new BABYLON.Observable();
  31120. }
  31121. return this._onAfterRenderObservable;
  31122. },
  31123. enumerable: true,
  31124. configurable: true
  31125. });
  31126. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31127. /**
  31128. * An event triggered before drawing the mesh
  31129. */
  31130. get: function () {
  31131. if (!this._onBeforeDrawObservable) {
  31132. this._onBeforeDrawObservable = new BABYLON.Observable();
  31133. }
  31134. return this._onBeforeDrawObservable;
  31135. },
  31136. enumerable: true,
  31137. configurable: true
  31138. });
  31139. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31140. set: function (callback) {
  31141. if (this._onBeforeDrawObserver) {
  31142. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31143. }
  31144. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31145. },
  31146. enumerable: true,
  31147. configurable: true
  31148. });
  31149. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31150. get: function () {
  31151. return this._morphTargetManager;
  31152. },
  31153. set: function (value) {
  31154. if (this._morphTargetManager === value) {
  31155. return;
  31156. }
  31157. this._morphTargetManager = value;
  31158. this._syncGeometryWithMorphTargetManager();
  31159. },
  31160. enumerable: true,
  31161. configurable: true
  31162. });
  31163. Object.defineProperty(Mesh.prototype, "source", {
  31164. get: function () {
  31165. return this._source;
  31166. },
  31167. enumerable: true,
  31168. configurable: true
  31169. });
  31170. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31171. get: function () {
  31172. return this._unIndexed;
  31173. },
  31174. set: function (value) {
  31175. if (this._unIndexed !== value) {
  31176. this._unIndexed = value;
  31177. this._markSubMeshesAsAttributesDirty();
  31178. }
  31179. },
  31180. enumerable: true,
  31181. configurable: true
  31182. });
  31183. // Methods
  31184. /**
  31185. * Returns the string "Mesh".
  31186. */
  31187. Mesh.prototype.getClassName = function () {
  31188. return "Mesh";
  31189. };
  31190. /**
  31191. * Returns a string.
  31192. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31193. */
  31194. Mesh.prototype.toString = function (fullDetails) {
  31195. var ret = _super.prototype.toString.call(this, fullDetails);
  31196. ret += ", n vertices: " + this.getTotalVertices();
  31197. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31198. if (this.animations) {
  31199. for (var i = 0; i < this.animations.length; i++) {
  31200. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31201. }
  31202. }
  31203. if (fullDetails) {
  31204. if (this._geometry) {
  31205. var ib = this.getIndices();
  31206. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31207. if (vb && ib) {
  31208. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31209. }
  31210. }
  31211. else {
  31212. ret += ", flat shading: UNKNOWN";
  31213. }
  31214. }
  31215. return ret;
  31216. };
  31217. Mesh.prototype._unBindEffect = function () {
  31218. _super.prototype._unBindEffect.call(this);
  31219. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31220. var instance = _a[_i];
  31221. instance._unBindEffect();
  31222. }
  31223. };
  31224. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31225. /**
  31226. * True if the mesh has some Levels Of Details (LOD).
  31227. * Returns a boolean.
  31228. */
  31229. get: function () {
  31230. return this._LODLevels.length > 0;
  31231. },
  31232. enumerable: true,
  31233. configurable: true
  31234. });
  31235. /**
  31236. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31237. * @returns an array of {BABYLON.MeshLODLevel}
  31238. */
  31239. Mesh.prototype.getLODLevels = function () {
  31240. return this._LODLevels;
  31241. };
  31242. Mesh.prototype._sortLODLevels = function () {
  31243. this._LODLevels.sort(function (a, b) {
  31244. if (a.distance < b.distance) {
  31245. return 1;
  31246. }
  31247. if (a.distance > b.distance) {
  31248. return -1;
  31249. }
  31250. return 0;
  31251. });
  31252. };
  31253. /**
  31254. * Add a mesh as LOD level triggered at the given distance.
  31255. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31256. * @param distance The distance from the center of the object to show this level
  31257. * @param mesh The mesh to be added as LOD level (can be null)
  31258. * @return This mesh (for chaining)
  31259. */
  31260. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31261. if (mesh && mesh._masterMesh) {
  31262. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31263. return this;
  31264. }
  31265. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31266. this._LODLevels.push(level);
  31267. if (mesh) {
  31268. mesh._masterMesh = this;
  31269. }
  31270. this._sortLODLevels();
  31271. return this;
  31272. };
  31273. /**
  31274. * Returns the LOD level mesh at the passed distance or null if not found.
  31275. * It is related to the method `addLODLevel(distance, mesh)`.
  31276. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31277. * Returns an object Mesh or `null`.
  31278. */
  31279. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31280. for (var index = 0; index < this._LODLevels.length; index++) {
  31281. var level = this._LODLevels[index];
  31282. if (level.distance === distance) {
  31283. return level.mesh;
  31284. }
  31285. }
  31286. return null;
  31287. };
  31288. /**
  31289. * Remove a mesh from the LOD array
  31290. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31291. * @param {Mesh} mesh The mesh to be removed.
  31292. * @return {Mesh} This mesh (for chaining)
  31293. */
  31294. Mesh.prototype.removeLODLevel = function (mesh) {
  31295. for (var index = 0; index < this._LODLevels.length; index++) {
  31296. if (this._LODLevels[index].mesh === mesh) {
  31297. this._LODLevels.splice(index, 1);
  31298. if (mesh) {
  31299. mesh._masterMesh = null;
  31300. }
  31301. }
  31302. }
  31303. this._sortLODLevels();
  31304. return this;
  31305. };
  31306. /**
  31307. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31308. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31309. */
  31310. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31311. if (!this._LODLevels || this._LODLevels.length === 0) {
  31312. return this;
  31313. }
  31314. var bSphere;
  31315. if (boundingSphere) {
  31316. bSphere = boundingSphere;
  31317. }
  31318. else {
  31319. var boundingInfo = this.getBoundingInfo();
  31320. bSphere = boundingInfo.boundingSphere;
  31321. }
  31322. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31323. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31324. if (this.onLODLevelSelection) {
  31325. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31326. }
  31327. return this;
  31328. }
  31329. for (var index = 0; index < this._LODLevels.length; index++) {
  31330. var level = this._LODLevels[index];
  31331. if (level.distance < distanceToCamera) {
  31332. if (level.mesh) {
  31333. level.mesh._preActivate();
  31334. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31335. }
  31336. if (this.onLODLevelSelection) {
  31337. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31338. }
  31339. return level.mesh;
  31340. }
  31341. }
  31342. if (this.onLODLevelSelection) {
  31343. this.onLODLevelSelection(distanceToCamera, this, this);
  31344. }
  31345. return this;
  31346. };
  31347. Object.defineProperty(Mesh.prototype, "geometry", {
  31348. /**
  31349. * Returns the mesh internal Geometry object.
  31350. */
  31351. get: function () {
  31352. return this._geometry;
  31353. },
  31354. enumerable: true,
  31355. configurable: true
  31356. });
  31357. /**
  31358. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31359. */
  31360. Mesh.prototype.getTotalVertices = function () {
  31361. if (this._geometry === null || this._geometry === undefined) {
  31362. return 0;
  31363. }
  31364. return this._geometry.getTotalVertices();
  31365. };
  31366. /**
  31367. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31368. * 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.
  31369. * You can force the copy with forceCopy === true
  31370. * Returns null if the mesh has no geometry or no vertex buffer.
  31371. * Possible `kind` values :
  31372. * - BABYLON.VertexBuffer.PositionKind
  31373. * - BABYLON.VertexBuffer.UVKind
  31374. * - BABYLON.VertexBuffer.UV2Kind
  31375. * - BABYLON.VertexBuffer.UV3Kind
  31376. * - BABYLON.VertexBuffer.UV4Kind
  31377. * - BABYLON.VertexBuffer.UV5Kind
  31378. * - BABYLON.VertexBuffer.UV6Kind
  31379. * - BABYLON.VertexBuffer.ColorKind
  31380. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31381. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31382. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31383. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31384. */
  31385. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31386. if (!this._geometry) {
  31387. return null;
  31388. }
  31389. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31390. };
  31391. /**
  31392. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31393. * Returns `null` if the mesh has no geometry.
  31394. * Possible `kind` values :
  31395. * - BABYLON.VertexBuffer.PositionKind
  31396. * - BABYLON.VertexBuffer.UVKind
  31397. * - BABYLON.VertexBuffer.UV2Kind
  31398. * - BABYLON.VertexBuffer.UV3Kind
  31399. * - BABYLON.VertexBuffer.UV4Kind
  31400. * - BABYLON.VertexBuffer.UV5Kind
  31401. * - BABYLON.VertexBuffer.UV6Kind
  31402. * - BABYLON.VertexBuffer.ColorKind
  31403. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31404. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31405. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31406. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31407. */
  31408. Mesh.prototype.getVertexBuffer = function (kind) {
  31409. if (!this._geometry) {
  31410. return null;
  31411. }
  31412. return this._geometry.getVertexBuffer(kind);
  31413. };
  31414. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31415. if (!this._geometry) {
  31416. if (this._delayInfo) {
  31417. return this._delayInfo.indexOf(kind) !== -1;
  31418. }
  31419. return false;
  31420. }
  31421. return this._geometry.isVerticesDataPresent(kind);
  31422. };
  31423. /**
  31424. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31425. * Possible `kind` values :
  31426. * - BABYLON.VertexBuffer.PositionKind
  31427. * - BABYLON.VertexBuffer.UVKind
  31428. * - BABYLON.VertexBuffer.UV2Kind
  31429. * - BABYLON.VertexBuffer.UV3Kind
  31430. * - BABYLON.VertexBuffer.UV4Kind
  31431. * - BABYLON.VertexBuffer.UV5Kind
  31432. * - BABYLON.VertexBuffer.UV6Kind
  31433. * - BABYLON.VertexBuffer.ColorKind
  31434. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31435. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31436. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31437. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31438. */
  31439. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31440. if (!this._geometry) {
  31441. if (this._delayInfo) {
  31442. return this._delayInfo.indexOf(kind) !== -1;
  31443. }
  31444. return false;
  31445. }
  31446. return this._geometry.isVertexBufferUpdatable(kind);
  31447. };
  31448. /**
  31449. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31450. * Possible `kind` values :
  31451. * - BABYLON.VertexBuffer.PositionKind
  31452. * - BABYLON.VertexBuffer.UVKind
  31453. * - BABYLON.VertexBuffer.UV2Kind
  31454. * - BABYLON.VertexBuffer.UV3Kind
  31455. * - BABYLON.VertexBuffer.UV4Kind
  31456. * - BABYLON.VertexBuffer.UV5Kind
  31457. * - BABYLON.VertexBuffer.UV6Kind
  31458. * - BABYLON.VertexBuffer.ColorKind
  31459. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31460. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31461. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31462. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31463. */
  31464. Mesh.prototype.getVerticesDataKinds = function () {
  31465. if (!this._geometry) {
  31466. var result = new Array();
  31467. if (this._delayInfo) {
  31468. this._delayInfo.forEach(function (kind, index, array) {
  31469. result.push(kind);
  31470. });
  31471. }
  31472. return result;
  31473. }
  31474. return this._geometry.getVerticesDataKinds();
  31475. };
  31476. /**
  31477. * Returns a positive integer : the total number of indices in this mesh geometry.
  31478. * Returns zero if the mesh has no geometry.
  31479. */
  31480. Mesh.prototype.getTotalIndices = function () {
  31481. if (!this._geometry) {
  31482. return 0;
  31483. }
  31484. return this._geometry.getTotalIndices();
  31485. };
  31486. /**
  31487. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31488. * 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.
  31489. * Returns an empty array if the mesh has no geometry.
  31490. */
  31491. Mesh.prototype.getIndices = function (copyWhenShared) {
  31492. if (!this._geometry) {
  31493. return [];
  31494. }
  31495. return this._geometry.getIndices(copyWhenShared);
  31496. };
  31497. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31498. get: function () {
  31499. return this._masterMesh !== null && this._masterMesh !== undefined;
  31500. },
  31501. enumerable: true,
  31502. configurable: true
  31503. });
  31504. /**
  31505. * Determine if the current mesh is ready to be rendered
  31506. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31507. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31508. * @returns true if all associated assets are ready (material, textures, shaders)
  31509. */
  31510. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31511. if (completeCheck === void 0) { completeCheck = false; }
  31512. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31513. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31514. return false;
  31515. }
  31516. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31517. return false;
  31518. }
  31519. if (!this.subMeshes || this.subMeshes.length === 0) {
  31520. return true;
  31521. }
  31522. if (!completeCheck) {
  31523. return true;
  31524. }
  31525. var engine = this.getEngine();
  31526. var scene = this.getScene();
  31527. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31528. this.computeWorldMatrix();
  31529. var mat = this.material || scene.defaultMaterial;
  31530. if (mat) {
  31531. if (mat.storeEffectOnSubMeshes) {
  31532. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31533. var subMesh = _a[_i];
  31534. var effectiveMaterial = subMesh.getMaterial();
  31535. if (effectiveMaterial) {
  31536. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31537. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31538. return false;
  31539. }
  31540. }
  31541. else {
  31542. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31543. return false;
  31544. }
  31545. }
  31546. }
  31547. }
  31548. }
  31549. else {
  31550. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31551. return false;
  31552. }
  31553. }
  31554. }
  31555. // Shadows
  31556. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31557. var light = _c[_b];
  31558. var generator = light.getShadowGenerator();
  31559. if (generator) {
  31560. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31561. var subMesh = _e[_d];
  31562. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31563. return false;
  31564. }
  31565. }
  31566. }
  31567. }
  31568. // LOD
  31569. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31570. var lod = _g[_f];
  31571. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31572. return false;
  31573. }
  31574. }
  31575. return true;
  31576. };
  31577. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31578. /**
  31579. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31580. * This property is pertinent only for updatable parametric shapes.
  31581. */
  31582. get: function () {
  31583. return this._areNormalsFrozen;
  31584. },
  31585. enumerable: true,
  31586. configurable: true
  31587. });
  31588. /**
  31589. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31590. * It has no effect at all on other shapes.
  31591. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31592. * Returns the Mesh.
  31593. */
  31594. Mesh.prototype.freezeNormals = function () {
  31595. this._areNormalsFrozen = true;
  31596. return this;
  31597. };
  31598. /**
  31599. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31600. * It has no effect at all on other shapes.
  31601. * It reactivates the mesh normals computation if it was previously frozen.
  31602. * Returns the Mesh.
  31603. */
  31604. Mesh.prototype.unfreezeNormals = function () {
  31605. this._areNormalsFrozen = false;
  31606. return this;
  31607. };
  31608. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31609. /**
  31610. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31611. */
  31612. set: function (count) {
  31613. this._overridenInstanceCount = count;
  31614. },
  31615. enumerable: true,
  31616. configurable: true
  31617. });
  31618. // Methods
  31619. Mesh.prototype._preActivate = function () {
  31620. var sceneRenderId = this.getScene().getRenderId();
  31621. if (this._preActivateId === sceneRenderId) {
  31622. return this;
  31623. }
  31624. this._preActivateId = sceneRenderId;
  31625. this._visibleInstances = null;
  31626. return this;
  31627. };
  31628. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31629. if (this._visibleInstances) {
  31630. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31631. }
  31632. return this;
  31633. };
  31634. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31635. if (!this._visibleInstances) {
  31636. this._visibleInstances = {};
  31637. this._visibleInstances.defaultRenderId = renderId;
  31638. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31639. }
  31640. if (!this._visibleInstances[renderId]) {
  31641. this._visibleInstances[renderId] = new Array();
  31642. }
  31643. this._visibleInstances[renderId].push(instance);
  31644. return this;
  31645. };
  31646. /**
  31647. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31648. * This means the mesh underlying bounding box and sphere are recomputed.
  31649. * Returns the Mesh.
  31650. */
  31651. Mesh.prototype.refreshBoundingInfo = function () {
  31652. return this._refreshBoundingInfo(false);
  31653. };
  31654. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31655. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31656. return this;
  31657. }
  31658. var data = this._getPositionData(applySkeleton);
  31659. if (data) {
  31660. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31661. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31662. }
  31663. if (this.subMeshes) {
  31664. for (var index = 0; index < this.subMeshes.length; index++) {
  31665. this.subMeshes[index].refreshBoundingInfo();
  31666. }
  31667. }
  31668. this._updateBoundingInfo();
  31669. return this;
  31670. };
  31671. Mesh.prototype._getPositionData = function (applySkeleton) {
  31672. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31673. if (data && applySkeleton && this.skeleton) {
  31674. data = BABYLON.Tools.Slice(data);
  31675. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31676. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31677. if (matricesWeightsData && matricesIndicesData) {
  31678. var needExtras = this.numBoneInfluencers > 4;
  31679. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31680. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31681. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31682. var tempVector = BABYLON.Tmp.Vector3[0];
  31683. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31684. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31685. var matWeightIdx = 0;
  31686. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31687. finalMatrix.reset();
  31688. var inf;
  31689. var weight;
  31690. for (inf = 0; inf < 4; inf++) {
  31691. weight = matricesWeightsData[matWeightIdx + inf];
  31692. if (weight > 0) {
  31693. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31694. finalMatrix.addToSelf(tempMatrix);
  31695. }
  31696. }
  31697. if (needExtras) {
  31698. for (inf = 0; inf < 4; inf++) {
  31699. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31700. if (weight > 0) {
  31701. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31702. finalMatrix.addToSelf(tempMatrix);
  31703. }
  31704. }
  31705. }
  31706. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31707. tempVector.toArray(data, index);
  31708. }
  31709. }
  31710. }
  31711. return data;
  31712. };
  31713. Mesh.prototype._createGlobalSubMesh = function (force) {
  31714. var totalVertices = this.getTotalVertices();
  31715. if (!totalVertices || !this.getIndices()) {
  31716. return null;
  31717. }
  31718. // Check if we need to recreate the submeshes
  31719. if (this.subMeshes && this.subMeshes.length > 0) {
  31720. var ib = this.getIndices();
  31721. if (!ib) {
  31722. return null;
  31723. }
  31724. var totalIndices = ib.length;
  31725. var needToRecreate = false;
  31726. if (force) {
  31727. needToRecreate = true;
  31728. }
  31729. else {
  31730. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31731. var submesh = _a[_i];
  31732. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31733. needToRecreate = true;
  31734. break;
  31735. }
  31736. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31737. needToRecreate = true;
  31738. break;
  31739. }
  31740. }
  31741. }
  31742. if (!needToRecreate) {
  31743. return this.subMeshes[0];
  31744. }
  31745. }
  31746. this.releaseSubMeshes();
  31747. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31748. };
  31749. Mesh.prototype.subdivide = function (count) {
  31750. if (count < 1) {
  31751. return;
  31752. }
  31753. var totalIndices = this.getTotalIndices();
  31754. var subdivisionSize = (totalIndices / count) | 0;
  31755. var offset = 0;
  31756. // Ensure that subdivisionSize is a multiple of 3
  31757. while (subdivisionSize % 3 !== 0) {
  31758. subdivisionSize++;
  31759. }
  31760. this.releaseSubMeshes();
  31761. for (var index = 0; index < count; index++) {
  31762. if (offset >= totalIndices) {
  31763. break;
  31764. }
  31765. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31766. offset += subdivisionSize;
  31767. }
  31768. this.synchronizeInstances();
  31769. };
  31770. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31771. if (updatable === void 0) { updatable = false; }
  31772. if (!this._geometry) {
  31773. var vertexData = new BABYLON.VertexData();
  31774. vertexData.set(data, kind);
  31775. var scene = this.getScene();
  31776. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31777. }
  31778. else {
  31779. this._geometry.setVerticesData(kind, data, updatable, stride);
  31780. }
  31781. return this;
  31782. };
  31783. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31784. if (updatable === void 0) { updatable = true; }
  31785. var vb = this.getVertexBuffer(kind);
  31786. if (!vb || vb.isUpdatable() === updatable) {
  31787. return;
  31788. }
  31789. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31790. };
  31791. /**
  31792. * Sets the mesh VertexBuffer.
  31793. * Returns the Mesh.
  31794. */
  31795. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31796. if (!this._geometry) {
  31797. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31798. }
  31799. this._geometry.setVerticesBuffer(buffer);
  31800. return this;
  31801. };
  31802. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31803. if (!this._geometry) {
  31804. return this;
  31805. }
  31806. if (!makeItUnique) {
  31807. this._geometry.updateVerticesData(kind, data, updateExtends);
  31808. }
  31809. else {
  31810. this.makeGeometryUnique();
  31811. this.updateVerticesData(kind, data, updateExtends, false);
  31812. }
  31813. return this;
  31814. };
  31815. /**
  31816. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31817. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31818. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31819. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31820. * Returns the Mesh.
  31821. */
  31822. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31823. if (computeNormals === void 0) { computeNormals = true; }
  31824. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31825. if (!positions) {
  31826. return this;
  31827. }
  31828. positionFunction(positions);
  31829. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31830. if (computeNormals) {
  31831. var indices = this.getIndices();
  31832. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31833. if (!normals) {
  31834. return this;
  31835. }
  31836. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31837. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31838. }
  31839. return this;
  31840. };
  31841. /**
  31842. * Creates a un-shared specific occurence of the geometry for the mesh.
  31843. * Returns the Mesh.
  31844. */
  31845. Mesh.prototype.makeGeometryUnique = function () {
  31846. if (!this._geometry) {
  31847. return this;
  31848. }
  31849. var oldGeometry = this._geometry;
  31850. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31851. oldGeometry.releaseForMesh(this, true);
  31852. geometry.applyToMesh(this);
  31853. return this;
  31854. };
  31855. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31856. if (totalVertices === void 0) { totalVertices = null; }
  31857. if (updatable === void 0) { updatable = false; }
  31858. if (!this._geometry) {
  31859. var vertexData = new BABYLON.VertexData();
  31860. vertexData.indices = indices;
  31861. var scene = this.getScene();
  31862. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31863. }
  31864. else {
  31865. this._geometry.setIndices(indices, totalVertices, updatable);
  31866. }
  31867. return this;
  31868. };
  31869. /**
  31870. * Update the current index buffer
  31871. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31872. * Returns the Mesh.
  31873. */
  31874. Mesh.prototype.updateIndices = function (indices, offset) {
  31875. if (!this._geometry) {
  31876. return this;
  31877. }
  31878. this._geometry.updateIndices(indices, offset);
  31879. return this;
  31880. };
  31881. /**
  31882. * Invert the geometry to move from a right handed system to a left handed one.
  31883. * Returns the Mesh.
  31884. */
  31885. Mesh.prototype.toLeftHanded = function () {
  31886. if (!this._geometry) {
  31887. return this;
  31888. }
  31889. this._geometry.toLeftHanded();
  31890. return this;
  31891. };
  31892. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31893. if (!this._geometry) {
  31894. return this;
  31895. }
  31896. var engine = this.getScene().getEngine();
  31897. // Wireframe
  31898. var indexToBind;
  31899. if (this._unIndexed) {
  31900. indexToBind = null;
  31901. }
  31902. else {
  31903. switch (fillMode) {
  31904. case BABYLON.Material.PointFillMode:
  31905. indexToBind = null;
  31906. break;
  31907. case BABYLON.Material.WireFrameFillMode:
  31908. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31909. break;
  31910. default:
  31911. case BABYLON.Material.TriangleFillMode:
  31912. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31913. break;
  31914. }
  31915. }
  31916. // VBOs
  31917. this._geometry._bind(effect, indexToBind);
  31918. return this;
  31919. };
  31920. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31921. if (alternate === void 0) { alternate = false; }
  31922. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31923. return this;
  31924. }
  31925. if (this._onBeforeDrawObservable) {
  31926. this._onBeforeDrawObservable.notifyObservers(this);
  31927. }
  31928. var scene = this.getScene();
  31929. var engine = scene.getEngine();
  31930. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31931. // or triangles as points
  31932. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31933. }
  31934. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31935. // Triangles as wireframe
  31936. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31937. }
  31938. else {
  31939. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31940. }
  31941. if (scene._isAlternateRenderingEnabled && !alternate) {
  31942. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31943. if (!effect || !scene.activeCamera) {
  31944. return this;
  31945. }
  31946. scene._switchToAlternateCameraConfiguration(true);
  31947. this._effectiveMaterial.bindView(effect);
  31948. this._effectiveMaterial.bindViewProjection(effect);
  31949. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31950. this._draw(subMesh, fillMode, instancesCount, true);
  31951. engine.setViewport(scene.activeCamera.viewport);
  31952. scene._switchToAlternateCameraConfiguration(false);
  31953. this._effectiveMaterial.bindView(effect);
  31954. this._effectiveMaterial.bindViewProjection(effect);
  31955. }
  31956. return this;
  31957. };
  31958. /**
  31959. * Registers for this mesh a javascript function called just before the rendering process.
  31960. * This function is passed the current mesh.
  31961. * Return the Mesh.
  31962. */
  31963. Mesh.prototype.registerBeforeRender = function (func) {
  31964. this.onBeforeRenderObservable.add(func);
  31965. return this;
  31966. };
  31967. /**
  31968. * Disposes a previously registered javascript function called before the rendering.
  31969. * This function is passed the current mesh.
  31970. * Returns the Mesh.
  31971. */
  31972. Mesh.prototype.unregisterBeforeRender = function (func) {
  31973. this.onBeforeRenderObservable.removeCallback(func);
  31974. return this;
  31975. };
  31976. /**
  31977. * Registers for this mesh a javascript function called just after the rendering is complete.
  31978. * This function is passed the current mesh.
  31979. * Returns the Mesh.
  31980. */
  31981. Mesh.prototype.registerAfterRender = function (func) {
  31982. this.onAfterRenderObservable.add(func);
  31983. return this;
  31984. };
  31985. /**
  31986. * Disposes a previously registered javascript function called after the rendering.
  31987. * This function is passed the current mesh.
  31988. * Return the Mesh.
  31989. */
  31990. Mesh.prototype.unregisterAfterRender = function (func) {
  31991. this.onAfterRenderObservable.removeCallback(func);
  31992. return this;
  31993. };
  31994. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31995. var scene = this.getScene();
  31996. this._batchCache.mustReturn = false;
  31997. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31998. this._batchCache.visibleInstances[subMeshId] = null;
  31999. if (this._visibleInstances) {
  32000. var currentRenderId = scene.getRenderId();
  32001. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32002. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32003. var selfRenderId = this._renderId;
  32004. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32005. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32006. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32007. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32008. }
  32009. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32010. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32011. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32012. this._batchCache.mustReturn = true;
  32013. return this._batchCache;
  32014. }
  32015. if (currentRenderId !== selfRenderId) {
  32016. this._batchCache.renderSelf[subMeshId] = false;
  32017. }
  32018. }
  32019. this._renderIdForInstances[subMeshId] = currentRenderId;
  32020. }
  32021. return this._batchCache;
  32022. };
  32023. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32024. var visibleInstances = batch.visibleInstances[subMesh._id];
  32025. if (!visibleInstances) {
  32026. return this;
  32027. }
  32028. var matricesCount = visibleInstances.length + 1;
  32029. var bufferSize = matricesCount * 16 * 4;
  32030. var currentInstancesBufferSize = this._instancesBufferSize;
  32031. var instancesBuffer = this._instancesBuffer;
  32032. while (this._instancesBufferSize < bufferSize) {
  32033. this._instancesBufferSize *= 2;
  32034. }
  32035. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32036. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32037. }
  32038. var offset = 0;
  32039. var instancesCount = 0;
  32040. var world = this.getWorldMatrix();
  32041. if (batch.renderSelf[subMesh._id]) {
  32042. world.copyToArray(this._instancesData, offset);
  32043. offset += 16;
  32044. instancesCount++;
  32045. }
  32046. if (visibleInstances) {
  32047. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32048. var instance = visibleInstances[instanceIndex];
  32049. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32050. offset += 16;
  32051. instancesCount++;
  32052. }
  32053. }
  32054. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32055. if (instancesBuffer) {
  32056. instancesBuffer.dispose();
  32057. }
  32058. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32059. this._instancesBuffer = instancesBuffer;
  32060. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32061. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32062. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32063. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32064. }
  32065. else {
  32066. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32067. }
  32068. this._bind(subMesh, effect, fillMode);
  32069. this._draw(subMesh, fillMode, instancesCount);
  32070. engine.unbindInstanceAttributes();
  32071. return this;
  32072. };
  32073. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32074. var scene = this.getScene();
  32075. var engine = scene.getEngine();
  32076. if (hardwareInstancedRendering) {
  32077. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32078. }
  32079. else {
  32080. if (batch.renderSelf[subMesh._id]) {
  32081. // Draw
  32082. if (onBeforeDraw) {
  32083. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32084. }
  32085. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32086. }
  32087. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32088. if (visibleInstancesForSubMesh) {
  32089. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32090. var instance = visibleInstancesForSubMesh[instanceIndex];
  32091. // World
  32092. var world = instance.getWorldMatrix();
  32093. if (onBeforeDraw) {
  32094. onBeforeDraw(true, world, effectiveMaterial);
  32095. }
  32096. // Draw
  32097. this._draw(subMesh, fillMode);
  32098. }
  32099. }
  32100. }
  32101. return this;
  32102. };
  32103. /**
  32104. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32105. * @param subMesh defines the subMesh to render
  32106. * @param enableAlphaMode defines if alpha mode can be changed
  32107. * @returns the current mesh
  32108. */
  32109. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32110. // this._checkOcclusionQuery();
  32111. // if (this._isOccluded) {
  32112. // return this;
  32113. // }
  32114. var scene = this.getScene();
  32115. // Managing instances
  32116. var batch = this._getInstancesRenderList(subMesh._id);
  32117. if (batch.mustReturn) {
  32118. return this;
  32119. }
  32120. // Checking geometry state
  32121. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32122. return this;
  32123. }
  32124. if (this._onBeforeRenderObservable) {
  32125. this._onBeforeRenderObservable.notifyObservers(this);
  32126. }
  32127. var engine = scene.getEngine();
  32128. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32129. // Material
  32130. var material = subMesh.getMaterial();
  32131. if (!material) {
  32132. return this;
  32133. }
  32134. this._effectiveMaterial = material;
  32135. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32136. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32137. return this;
  32138. }
  32139. }
  32140. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32141. return this;
  32142. }
  32143. // Alpha mode
  32144. if (enableAlphaMode) {
  32145. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32146. }
  32147. // Outline - step 1
  32148. var savedDepthWrite = engine.getDepthWrite();
  32149. if (this.renderOutline) {
  32150. engine.setDepthWrite(false);
  32151. scene.getOutlineRenderer().render(subMesh, batch);
  32152. engine.setDepthWrite(savedDepthWrite);
  32153. }
  32154. var effect;
  32155. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32156. effect = subMesh.effect;
  32157. }
  32158. else {
  32159. effect = this._effectiveMaterial.getEffect();
  32160. }
  32161. if (!effect) {
  32162. return this;
  32163. }
  32164. var sideOrientation = this.overrideMaterialSideOrientation;
  32165. if (sideOrientation == null) {
  32166. sideOrientation = this._effectiveMaterial.sideOrientation;
  32167. if (this._getWorldMatrixDeterminant() < 0) {
  32168. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32169. }
  32170. }
  32171. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32172. if (this._effectiveMaterial.forceDepthWrite) {
  32173. engine.setDepthWrite(true);
  32174. }
  32175. // Bind
  32176. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32177. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32178. this._bind(subMesh, effect, fillMode);
  32179. }
  32180. var world = this.getWorldMatrix();
  32181. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32182. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32183. }
  32184. else {
  32185. this._effectiveMaterial.bind(world, this);
  32186. }
  32187. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32188. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32189. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32190. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32191. }
  32192. // Draw
  32193. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32194. // Unbind
  32195. this._effectiveMaterial.unbind();
  32196. // Outline - step 2
  32197. if (this.renderOutline && savedDepthWrite) {
  32198. engine.setDepthWrite(true);
  32199. engine.setColorWrite(false);
  32200. scene.getOutlineRenderer().render(subMesh, batch);
  32201. engine.setColorWrite(true);
  32202. }
  32203. // Overlay
  32204. if (this.renderOverlay) {
  32205. var currentMode = engine.getAlphaMode();
  32206. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32207. scene.getOutlineRenderer().render(subMesh, batch, true);
  32208. engine.setAlphaMode(currentMode);
  32209. }
  32210. if (this._onAfterRenderObservable) {
  32211. this._onAfterRenderObservable.notifyObservers(this);
  32212. }
  32213. return this;
  32214. };
  32215. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32216. if (isInstance && effectiveMaterial) {
  32217. effectiveMaterial.bindOnlyWorldMatrix(world);
  32218. }
  32219. };
  32220. /**
  32221. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32222. */
  32223. Mesh.prototype.getEmittedParticleSystems = function () {
  32224. var results = new Array();
  32225. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32226. var particleSystem = this.getScene().particleSystems[index];
  32227. if (particleSystem.emitter === this) {
  32228. results.push(particleSystem);
  32229. }
  32230. }
  32231. return results;
  32232. };
  32233. /**
  32234. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32235. */
  32236. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32237. var results = new Array();
  32238. var descendants = this.getDescendants();
  32239. descendants.push(this);
  32240. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32241. var particleSystem = this.getScene().particleSystems[index];
  32242. var emitter = particleSystem.emitter;
  32243. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32244. results.push(particleSystem);
  32245. }
  32246. }
  32247. return results;
  32248. };
  32249. /**
  32250. * Normalize matrix weights so that all vertices have a total weight set to 1
  32251. */
  32252. Mesh.prototype.cleanMatrixWeights = function () {
  32253. var epsilon = 1e-3;
  32254. var noInfluenceBoneIndex = 0.0;
  32255. if (this.skeleton) {
  32256. noInfluenceBoneIndex = this.skeleton.bones.length;
  32257. }
  32258. else {
  32259. return;
  32260. }
  32261. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32262. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32263. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32264. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32265. var influencers = this.numBoneInfluencers;
  32266. var size = matricesWeights.length;
  32267. for (var i = 0; i < size; i += 4) {
  32268. var weight = 0.0;
  32269. var firstZeroWeight = -1;
  32270. for (var j = 0; j < 4; j++) {
  32271. var w = matricesWeights[i + j];
  32272. weight += w;
  32273. if (w < epsilon && firstZeroWeight < 0) {
  32274. firstZeroWeight = j;
  32275. }
  32276. }
  32277. if (matricesWeightsExtra) {
  32278. for (var j = 0; j < 4; j++) {
  32279. var w = matricesWeightsExtra[i + j];
  32280. weight += w;
  32281. if (w < epsilon && firstZeroWeight < 0) {
  32282. firstZeroWeight = j + 4;
  32283. }
  32284. }
  32285. }
  32286. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32287. firstZeroWeight = influencers - 1;
  32288. }
  32289. if (weight > epsilon) {
  32290. var mweight = 1.0 / weight;
  32291. for (var j = 0; j < 4; j++) {
  32292. matricesWeights[i + j] *= mweight;
  32293. }
  32294. if (matricesWeightsExtra) {
  32295. for (var j = 0; j < 4; j++) {
  32296. matricesWeightsExtra[i + j] *= mweight;
  32297. }
  32298. }
  32299. }
  32300. else {
  32301. if (firstZeroWeight >= 4) {
  32302. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32303. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32304. }
  32305. else {
  32306. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32307. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32308. }
  32309. }
  32310. }
  32311. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32312. if (matricesIndicesExtra) {
  32313. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32314. }
  32315. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32316. if (matricesWeightsExtra) {
  32317. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32318. }
  32319. };
  32320. Mesh.prototype._checkDelayState = function () {
  32321. var scene = this.getScene();
  32322. if (this._geometry) {
  32323. this._geometry.load(scene);
  32324. }
  32325. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32326. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32327. this._queueLoad(scene);
  32328. }
  32329. return this;
  32330. };
  32331. Mesh.prototype._queueLoad = function (scene) {
  32332. var _this = this;
  32333. scene._addPendingData(this);
  32334. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32335. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32336. if (data instanceof ArrayBuffer) {
  32337. _this._delayLoadingFunction(data, _this);
  32338. }
  32339. else {
  32340. _this._delayLoadingFunction(JSON.parse(data), _this);
  32341. }
  32342. _this.instances.forEach(function (instance) {
  32343. instance._syncSubMeshes();
  32344. });
  32345. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32346. scene._removePendingData(_this);
  32347. }, function () { }, scene.database, getBinaryData);
  32348. return this;
  32349. };
  32350. /**
  32351. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32352. */
  32353. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32354. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32355. return false;
  32356. }
  32357. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32358. return false;
  32359. }
  32360. this._checkDelayState();
  32361. return true;
  32362. };
  32363. /**
  32364. * Sets the mesh material by the material or multiMaterial `id` property.
  32365. * The material `id` is a string identifying the material or the multiMaterial.
  32366. * This method returns the Mesh.
  32367. */
  32368. Mesh.prototype.setMaterialByID = function (id) {
  32369. var materials = this.getScene().materials;
  32370. var index;
  32371. for (index = materials.length - 1; index > -1; index--) {
  32372. if (materials[index].id === id) {
  32373. this.material = materials[index];
  32374. return this;
  32375. }
  32376. }
  32377. // Multi
  32378. var multiMaterials = this.getScene().multiMaterials;
  32379. for (index = multiMaterials.length - 1; index > -1; index--) {
  32380. if (multiMaterials[index].id === id) {
  32381. this.material = multiMaterials[index];
  32382. return this;
  32383. }
  32384. }
  32385. return this;
  32386. };
  32387. /**
  32388. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32389. */
  32390. Mesh.prototype.getAnimatables = function () {
  32391. var results = new Array();
  32392. if (this.material) {
  32393. results.push(this.material);
  32394. }
  32395. if (this.skeleton) {
  32396. results.push(this.skeleton);
  32397. }
  32398. return results;
  32399. };
  32400. /**
  32401. * Modifies the mesh geometry according to the passed transformation matrix.
  32402. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32403. * The mesh normals are modified accordingly the same transformation.
  32404. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32405. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32406. * Returns the Mesh.
  32407. */
  32408. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32409. // Position
  32410. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32411. return this;
  32412. }
  32413. var submeshes = this.subMeshes.splice(0);
  32414. this._resetPointsArrayCache();
  32415. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32416. var temp = new Array();
  32417. var index;
  32418. for (index = 0; index < data.length; index += 3) {
  32419. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32420. }
  32421. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32422. // Normals
  32423. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32424. return this;
  32425. }
  32426. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32427. temp = [];
  32428. for (index = 0; index < data.length; index += 3) {
  32429. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32430. }
  32431. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32432. // flip faces?
  32433. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32434. this.flipFaces();
  32435. }
  32436. // Restore submeshes
  32437. this.releaseSubMeshes();
  32438. this.subMeshes = submeshes;
  32439. return this;
  32440. };
  32441. /**
  32442. * Modifies the mesh geometry according to its own current World Matrix.
  32443. * The mesh World Matrix is then reset.
  32444. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32445. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32446. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32447. * Returns the Mesh.
  32448. */
  32449. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32450. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32451. this.scaling.copyFromFloats(1, 1, 1);
  32452. this.position.copyFromFloats(0, 0, 0);
  32453. this.rotation.copyFromFloats(0, 0, 0);
  32454. //only if quaternion is already set
  32455. if (this.rotationQuaternion) {
  32456. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32457. }
  32458. this._worldMatrix = BABYLON.Matrix.Identity();
  32459. return this;
  32460. };
  32461. Object.defineProperty(Mesh.prototype, "_positions", {
  32462. // Cache
  32463. get: function () {
  32464. if (this._geometry) {
  32465. return this._geometry._positions;
  32466. }
  32467. return null;
  32468. },
  32469. enumerable: true,
  32470. configurable: true
  32471. });
  32472. Mesh.prototype._resetPointsArrayCache = function () {
  32473. if (this._geometry) {
  32474. this._geometry._resetPointsArrayCache();
  32475. }
  32476. return this;
  32477. };
  32478. Mesh.prototype._generatePointsArray = function () {
  32479. if (this._geometry) {
  32480. return this._geometry._generatePointsArray();
  32481. }
  32482. return false;
  32483. };
  32484. /**
  32485. * Returns a new Mesh object generated from the current mesh properties.
  32486. * This method must not get confused with createInstance().
  32487. * The parameter `name` is a string, the name given to the new mesh.
  32488. * The optional parameter `newParent` can be any Node object (default `null`).
  32489. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32490. * 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.
  32491. */
  32492. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32493. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32494. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32495. };
  32496. /**
  32497. * Releases resources associated with this mesh.
  32498. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32499. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32500. */
  32501. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32502. var _this = this;
  32503. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32504. this.morphTargetManager = null;
  32505. if (this._geometry) {
  32506. this._geometry.releaseForMesh(this, true);
  32507. }
  32508. if (this._onBeforeDrawObservable) {
  32509. this._onBeforeDrawObservable.clear();
  32510. }
  32511. if (this._onBeforeRenderObservable) {
  32512. this._onBeforeRenderObservable.clear();
  32513. }
  32514. if (this._onAfterRenderObservable) {
  32515. this._onAfterRenderObservable.clear();
  32516. }
  32517. // Sources
  32518. var meshes = this.getScene().meshes;
  32519. meshes.forEach(function (abstractMesh) {
  32520. var mesh = abstractMesh;
  32521. if (mesh._source && mesh._source === _this) {
  32522. mesh._source = null;
  32523. }
  32524. });
  32525. this._source = null;
  32526. // Instances
  32527. if (this._instancesBuffer) {
  32528. this._instancesBuffer.dispose();
  32529. this._instancesBuffer = null;
  32530. }
  32531. while (this.instances.length) {
  32532. this.instances[0].dispose();
  32533. }
  32534. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32535. };
  32536. /**
  32537. * Modifies the mesh geometry according to a displacement map.
  32538. * 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.
  32539. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32540. * This method returns nothing.
  32541. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32542. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32543. * 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.
  32544. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32545. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32546. *
  32547. * Returns the Mesh.
  32548. */
  32549. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32550. var _this = this;
  32551. var scene = this.getScene();
  32552. var onload = function (img) {
  32553. // Getting height map data
  32554. var canvas = document.createElement("canvas");
  32555. var context = canvas.getContext("2d");
  32556. var heightMapWidth = img.width;
  32557. var heightMapHeight = img.height;
  32558. canvas.width = heightMapWidth;
  32559. canvas.height = heightMapHeight;
  32560. context.drawImage(img, 0, 0);
  32561. // Create VertexData from map data
  32562. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32563. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32564. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32565. //execute success callback, if set
  32566. if (onSuccess) {
  32567. onSuccess(_this);
  32568. }
  32569. };
  32570. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32571. return this;
  32572. };
  32573. /**
  32574. * Modifies the mesh geometry according to a displacementMap buffer.
  32575. * 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.
  32576. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32577. * This method returns nothing.
  32578. * 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.
  32579. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32580. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32581. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32582. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32583. *
  32584. * Returns the Mesh.
  32585. */
  32586. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32587. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32588. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32589. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32590. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32591. return this;
  32592. }
  32593. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32594. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32595. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32596. var position = BABYLON.Vector3.Zero();
  32597. var normal = BABYLON.Vector3.Zero();
  32598. var uv = BABYLON.Vector2.Zero();
  32599. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32600. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32601. for (var index = 0; index < positions.length; index += 3) {
  32602. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32603. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32604. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32605. // Compute height
  32606. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32607. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32608. var pos = (u + v * heightMapWidth) * 4;
  32609. var r = buffer[pos] / 255.0;
  32610. var g = buffer[pos + 1] / 255.0;
  32611. var b = buffer[pos + 2] / 255.0;
  32612. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32613. normal.normalize();
  32614. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32615. position = position.add(normal);
  32616. position.toArray(positions, index);
  32617. }
  32618. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32619. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32620. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32621. return this;
  32622. };
  32623. /**
  32624. * Modify the mesh to get a flat shading rendering.
  32625. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32626. * This method returns the Mesh.
  32627. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32628. */
  32629. Mesh.prototype.convertToFlatShadedMesh = function () {
  32630. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32631. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32632. var kinds = this.getVerticesDataKinds();
  32633. var vbs = {};
  32634. var data = {};
  32635. var newdata = {};
  32636. var updatableNormals = false;
  32637. var kindIndex;
  32638. var kind;
  32639. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32640. kind = kinds[kindIndex];
  32641. var vertexBuffer = this.getVertexBuffer(kind);
  32642. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32643. updatableNormals = vertexBuffer.isUpdatable();
  32644. kinds.splice(kindIndex, 1);
  32645. kindIndex--;
  32646. continue;
  32647. }
  32648. vbs[kind] = vertexBuffer;
  32649. data[kind] = vbs[kind].getData();
  32650. newdata[kind] = [];
  32651. }
  32652. // Save previous submeshes
  32653. var previousSubmeshes = this.subMeshes.slice(0);
  32654. var indices = this.getIndices();
  32655. var totalIndices = this.getTotalIndices();
  32656. // Generating unique vertices per face
  32657. var index;
  32658. for (index = 0; index < totalIndices; index++) {
  32659. var vertexIndex = indices[index];
  32660. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32661. kind = kinds[kindIndex];
  32662. var stride = vbs[kind].getStrideSize();
  32663. for (var offset = 0; offset < stride; offset++) {
  32664. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32665. }
  32666. }
  32667. }
  32668. // Updating faces & normal
  32669. var normals = [];
  32670. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32671. for (index = 0; index < totalIndices; index += 3) {
  32672. indices[index] = index;
  32673. indices[index + 1] = index + 1;
  32674. indices[index + 2] = index + 2;
  32675. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32676. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32677. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32678. var p1p2 = p1.subtract(p2);
  32679. var p3p2 = p3.subtract(p2);
  32680. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32681. // Store same normals for every vertex
  32682. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32683. normals.push(normal.x);
  32684. normals.push(normal.y);
  32685. normals.push(normal.z);
  32686. }
  32687. }
  32688. this.setIndices(indices);
  32689. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32690. // Updating vertex buffers
  32691. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32692. kind = kinds[kindIndex];
  32693. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32694. }
  32695. // Updating submeshes
  32696. this.releaseSubMeshes();
  32697. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32698. var previousOne = previousSubmeshes[submeshIndex];
  32699. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32700. }
  32701. this.synchronizeInstances();
  32702. return this;
  32703. };
  32704. /**
  32705. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32706. * In other words, more vertices, no more indices and a single bigger VBO.
  32707. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32708. * Returns the Mesh.
  32709. */
  32710. Mesh.prototype.convertToUnIndexedMesh = function () {
  32711. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32712. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32713. var kinds = this.getVerticesDataKinds();
  32714. var vbs = {};
  32715. var data = {};
  32716. var newdata = {};
  32717. var kindIndex;
  32718. var kind;
  32719. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32720. kind = kinds[kindIndex];
  32721. var vertexBuffer = this.getVertexBuffer(kind);
  32722. vbs[kind] = vertexBuffer;
  32723. data[kind] = vbs[kind].getData();
  32724. newdata[kind] = [];
  32725. }
  32726. // Save previous submeshes
  32727. var previousSubmeshes = this.subMeshes.slice(0);
  32728. var indices = this.getIndices();
  32729. var totalIndices = this.getTotalIndices();
  32730. // Generating unique vertices per face
  32731. var index;
  32732. for (index = 0; index < totalIndices; index++) {
  32733. var vertexIndex = indices[index];
  32734. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32735. kind = kinds[kindIndex];
  32736. var stride = vbs[kind].getStrideSize();
  32737. for (var offset = 0; offset < stride; offset++) {
  32738. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32739. }
  32740. }
  32741. }
  32742. // Updating indices
  32743. for (index = 0; index < totalIndices; index += 3) {
  32744. indices[index] = index;
  32745. indices[index + 1] = index + 1;
  32746. indices[index + 2] = index + 2;
  32747. }
  32748. this.setIndices(indices);
  32749. // Updating vertex buffers
  32750. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32751. kind = kinds[kindIndex];
  32752. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32753. }
  32754. // Updating submeshes
  32755. this.releaseSubMeshes();
  32756. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32757. var previousOne = previousSubmeshes[submeshIndex];
  32758. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32759. }
  32760. this._unIndexed = true;
  32761. this.synchronizeInstances();
  32762. return this;
  32763. };
  32764. /**
  32765. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32766. * This method returns the Mesh.
  32767. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32768. */
  32769. Mesh.prototype.flipFaces = function (flipNormals) {
  32770. if (flipNormals === void 0) { flipNormals = false; }
  32771. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32772. var i;
  32773. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32774. for (i = 0; i < vertex_data.normals.length; i++) {
  32775. vertex_data.normals[i] *= -1;
  32776. }
  32777. }
  32778. if (vertex_data.indices) {
  32779. var temp;
  32780. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32781. // reassign indices
  32782. temp = vertex_data.indices[i + 1];
  32783. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32784. vertex_data.indices[i + 2] = temp;
  32785. }
  32786. }
  32787. vertex_data.applyToMesh(this);
  32788. return this;
  32789. };
  32790. // Instances
  32791. /**
  32792. * Creates a new InstancedMesh object from the mesh model.
  32793. * An instance shares the same properties and the same material than its model.
  32794. * Only these properties of each instance can then be set individually :
  32795. * - position
  32796. * - rotation
  32797. * - rotationQuaternion
  32798. * - setPivotMatrix
  32799. * - scaling
  32800. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32801. * Warning : this method is not supported for Line mesh and LineSystem
  32802. */
  32803. Mesh.prototype.createInstance = function (name) {
  32804. return new BABYLON.InstancedMesh(name, this);
  32805. };
  32806. /**
  32807. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32808. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32809. * This method returns the Mesh.
  32810. */
  32811. Mesh.prototype.synchronizeInstances = function () {
  32812. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32813. var instance = this.instances[instanceIndex];
  32814. instance._syncSubMeshes();
  32815. }
  32816. return this;
  32817. };
  32818. /**
  32819. * Simplify the mesh according to the given array of settings.
  32820. * Function will return immediately and will simplify async. It returns the Mesh.
  32821. * @param settings a collection of simplification settings.
  32822. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32823. * @param type the type of simplification to run.
  32824. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32825. */
  32826. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32827. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32828. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32829. this.getScene().simplificationQueue.addTask({
  32830. settings: settings,
  32831. parallelProcessing: parallelProcessing,
  32832. mesh: this,
  32833. simplificationType: simplificationType,
  32834. successCallback: successCallback
  32835. });
  32836. return this;
  32837. };
  32838. /**
  32839. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32840. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32841. * This should be used together with the simplification to avoid disappearing triangles.
  32842. * Returns the Mesh.
  32843. * @param successCallback an optional success callback to be called after the optimization finished.
  32844. */
  32845. Mesh.prototype.optimizeIndices = function (successCallback) {
  32846. var _this = this;
  32847. var indices = this.getIndices();
  32848. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32849. if (!positions || !indices) {
  32850. return this;
  32851. }
  32852. var vectorPositions = new Array();
  32853. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32854. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32855. }
  32856. var dupes = new Array();
  32857. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32858. var realPos = vectorPositions.length - 1 - iteration;
  32859. var testedPosition = vectorPositions[realPos];
  32860. for (var j = 0; j < realPos; ++j) {
  32861. var againstPosition = vectorPositions[j];
  32862. if (testedPosition.equals(againstPosition)) {
  32863. dupes[realPos] = j;
  32864. break;
  32865. }
  32866. }
  32867. }, function () {
  32868. for (var i = 0; i < indices.length; ++i) {
  32869. indices[i] = dupes[indices[i]] || indices[i];
  32870. }
  32871. //indices are now reordered
  32872. var originalSubMeshes = _this.subMeshes.slice(0);
  32873. _this.setIndices(indices);
  32874. _this.subMeshes = originalSubMeshes;
  32875. if (successCallback) {
  32876. successCallback(_this);
  32877. }
  32878. });
  32879. return this;
  32880. };
  32881. Mesh.prototype.serialize = function (serializationObject) {
  32882. serializationObject.name = this.name;
  32883. serializationObject.id = this.id;
  32884. serializationObject.type = this.getClassName();
  32885. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32886. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32887. }
  32888. serializationObject.position = this.position.asArray();
  32889. if (this.rotationQuaternion) {
  32890. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32891. }
  32892. else if (this.rotation) {
  32893. serializationObject.rotation = this.rotation.asArray();
  32894. }
  32895. serializationObject.scaling = this.scaling.asArray();
  32896. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32897. serializationObject.isEnabled = this.isEnabled(false);
  32898. serializationObject.isVisible = this.isVisible;
  32899. serializationObject.infiniteDistance = this.infiniteDistance;
  32900. serializationObject.pickable = this.isPickable;
  32901. serializationObject.receiveShadows = this.receiveShadows;
  32902. serializationObject.billboardMode = this.billboardMode;
  32903. serializationObject.visibility = this.visibility;
  32904. serializationObject.checkCollisions = this.checkCollisions;
  32905. serializationObject.isBlocker = this.isBlocker;
  32906. // Parent
  32907. if (this.parent) {
  32908. serializationObject.parentId = this.parent.id;
  32909. }
  32910. // Geometry
  32911. serializationObject.isUnIndexed = this.isUnIndexed;
  32912. var geometry = this._geometry;
  32913. if (geometry) {
  32914. var geometryId = geometry.id;
  32915. serializationObject.geometryId = geometryId;
  32916. // SubMeshes
  32917. serializationObject.subMeshes = [];
  32918. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32919. var subMesh = this.subMeshes[subIndex];
  32920. serializationObject.subMeshes.push({
  32921. materialIndex: subMesh.materialIndex,
  32922. verticesStart: subMesh.verticesStart,
  32923. verticesCount: subMesh.verticesCount,
  32924. indexStart: subMesh.indexStart,
  32925. indexCount: subMesh.indexCount
  32926. });
  32927. }
  32928. }
  32929. // Material
  32930. if (this.material) {
  32931. serializationObject.materialId = this.material.id;
  32932. }
  32933. else {
  32934. this.material = null;
  32935. }
  32936. // Morph targets
  32937. if (this.morphTargetManager) {
  32938. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32939. }
  32940. // Skeleton
  32941. if (this.skeleton) {
  32942. serializationObject.skeletonId = this.skeleton.id;
  32943. }
  32944. // Physics
  32945. //TODO implement correct serialization for physics impostors.
  32946. var impostor = this.getPhysicsImpostor();
  32947. if (impostor) {
  32948. serializationObject.physicsMass = impostor.getParam("mass");
  32949. serializationObject.physicsFriction = impostor.getParam("friction");
  32950. serializationObject.physicsRestitution = impostor.getParam("mass");
  32951. serializationObject.physicsImpostor = impostor.type;
  32952. }
  32953. // Metadata
  32954. if (this.metadata) {
  32955. serializationObject.metadata = this.metadata;
  32956. }
  32957. // Instances
  32958. serializationObject.instances = [];
  32959. for (var index = 0; index < this.instances.length; index++) {
  32960. var instance = this.instances[index];
  32961. var serializationInstance = {
  32962. name: instance.name,
  32963. id: instance.id,
  32964. position: instance.position.asArray(),
  32965. scaling: instance.scaling.asArray()
  32966. };
  32967. if (instance.rotationQuaternion) {
  32968. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32969. }
  32970. else if (instance.rotation) {
  32971. serializationInstance.rotation = instance.rotation.asArray();
  32972. }
  32973. serializationObject.instances.push(serializationInstance);
  32974. // Animations
  32975. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32976. serializationInstance.ranges = instance.serializeAnimationRanges();
  32977. }
  32978. //
  32979. // Animations
  32980. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32981. serializationObject.ranges = this.serializeAnimationRanges();
  32982. // Layer mask
  32983. serializationObject.layerMask = this.layerMask;
  32984. // Alpha
  32985. serializationObject.alphaIndex = this.alphaIndex;
  32986. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32987. // Overlay
  32988. serializationObject.overlayAlpha = this.overlayAlpha;
  32989. serializationObject.overlayColor = this.overlayColor.asArray();
  32990. serializationObject.renderOverlay = this.renderOverlay;
  32991. // Fog
  32992. serializationObject.applyFog = this.applyFog;
  32993. // Action Manager
  32994. if (this.actionManager) {
  32995. serializationObject.actions = this.actionManager.serialize(this.name);
  32996. }
  32997. };
  32998. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32999. if (!this.geometry) {
  33000. return;
  33001. }
  33002. this._markSubMeshesAsAttributesDirty();
  33003. var morphTargetManager = this._morphTargetManager;
  33004. if (morphTargetManager && morphTargetManager.vertexCount) {
  33005. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33006. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33007. this.morphTargetManager = null;
  33008. return;
  33009. }
  33010. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33011. var morphTarget = morphTargetManager.getActiveTarget(index);
  33012. var positions = morphTarget.getPositions();
  33013. if (!positions) {
  33014. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33015. return;
  33016. }
  33017. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33018. var normals = morphTarget.getNormals();
  33019. if (normals) {
  33020. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33021. }
  33022. var tangents = morphTarget.getTangents();
  33023. if (tangents) {
  33024. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33025. }
  33026. }
  33027. }
  33028. else {
  33029. var index = 0;
  33030. // Positions
  33031. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33032. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33033. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33034. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33035. }
  33036. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33037. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33038. }
  33039. index++;
  33040. }
  33041. }
  33042. };
  33043. // Statics
  33044. /**
  33045. * Returns a new Mesh object parsed from the source provided.
  33046. * The parameter `parsedMesh` is the source.
  33047. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33048. */
  33049. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33050. var mesh;
  33051. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33052. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33053. }
  33054. else {
  33055. mesh = new Mesh(parsedMesh.name, scene);
  33056. }
  33057. mesh.id = parsedMesh.id;
  33058. if (BABYLON.Tags) {
  33059. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33060. }
  33061. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33062. if (parsedMesh.metadata !== undefined) {
  33063. mesh.metadata = parsedMesh.metadata;
  33064. }
  33065. if (parsedMesh.rotationQuaternion) {
  33066. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33067. }
  33068. else if (parsedMesh.rotation) {
  33069. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33070. }
  33071. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33072. if (parsedMesh.localMatrix) {
  33073. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33074. }
  33075. else if (parsedMesh.pivotMatrix) {
  33076. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33077. }
  33078. mesh.setEnabled(parsedMesh.isEnabled);
  33079. mesh.isVisible = parsedMesh.isVisible;
  33080. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33081. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33082. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33083. if (parsedMesh.applyFog !== undefined) {
  33084. mesh.applyFog = parsedMesh.applyFog;
  33085. }
  33086. if (parsedMesh.pickable !== undefined) {
  33087. mesh.isPickable = parsedMesh.pickable;
  33088. }
  33089. if (parsedMesh.alphaIndex !== undefined) {
  33090. mesh.alphaIndex = parsedMesh.alphaIndex;
  33091. }
  33092. mesh.receiveShadows = parsedMesh.receiveShadows;
  33093. mesh.billboardMode = parsedMesh.billboardMode;
  33094. if (parsedMesh.visibility !== undefined) {
  33095. mesh.visibility = parsedMesh.visibility;
  33096. }
  33097. mesh.checkCollisions = parsedMesh.checkCollisions;
  33098. if (parsedMesh.isBlocker !== undefined) {
  33099. mesh.isBlocker = parsedMesh.isBlocker;
  33100. }
  33101. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33102. // freezeWorldMatrix
  33103. if (parsedMesh.freezeWorldMatrix) {
  33104. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33105. }
  33106. // Parent
  33107. if (parsedMesh.parentId) {
  33108. mesh._waitingParentId = parsedMesh.parentId;
  33109. }
  33110. // Actions
  33111. if (parsedMesh.actions !== undefined) {
  33112. mesh._waitingActions = parsedMesh.actions;
  33113. }
  33114. // Overlay
  33115. if (parsedMesh.overlayAlpha !== undefined) {
  33116. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33117. }
  33118. if (parsedMesh.overlayColor !== undefined) {
  33119. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33120. }
  33121. if (parsedMesh.renderOverlay !== undefined) {
  33122. mesh.renderOverlay = parsedMesh.renderOverlay;
  33123. }
  33124. // Geometry
  33125. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33126. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33127. if (parsedMesh.delayLoadingFile) {
  33128. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33129. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33130. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33131. if (parsedMesh._binaryInfo) {
  33132. mesh._binaryInfo = parsedMesh._binaryInfo;
  33133. }
  33134. mesh._delayInfo = [];
  33135. if (parsedMesh.hasUVs) {
  33136. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33137. }
  33138. if (parsedMesh.hasUVs2) {
  33139. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33140. }
  33141. if (parsedMesh.hasUVs3) {
  33142. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33143. }
  33144. if (parsedMesh.hasUVs4) {
  33145. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33146. }
  33147. if (parsedMesh.hasUVs5) {
  33148. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33149. }
  33150. if (parsedMesh.hasUVs6) {
  33151. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33152. }
  33153. if (parsedMesh.hasColors) {
  33154. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33155. }
  33156. if (parsedMesh.hasMatricesIndices) {
  33157. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33158. }
  33159. if (parsedMesh.hasMatricesWeights) {
  33160. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33161. }
  33162. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33163. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33164. mesh._checkDelayState();
  33165. }
  33166. }
  33167. else {
  33168. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33169. }
  33170. // Material
  33171. if (parsedMesh.materialId) {
  33172. mesh.setMaterialByID(parsedMesh.materialId);
  33173. }
  33174. else {
  33175. mesh.material = null;
  33176. }
  33177. // Morph targets
  33178. if (parsedMesh.morphTargetManagerId > -1) {
  33179. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33180. }
  33181. // Skeleton
  33182. if (parsedMesh.skeletonId > -1) {
  33183. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33184. if (parsedMesh.numBoneInfluencers) {
  33185. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33186. }
  33187. }
  33188. // Animations
  33189. if (parsedMesh.animations) {
  33190. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33191. var parsedAnimation = parsedMesh.animations[animationIndex];
  33192. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33193. }
  33194. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33195. }
  33196. if (parsedMesh.autoAnimate) {
  33197. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33198. }
  33199. // Layer Mask
  33200. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33201. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33202. }
  33203. else {
  33204. mesh.layerMask = 0x0FFFFFFF;
  33205. }
  33206. // Physics
  33207. if (parsedMesh.physicsImpostor) {
  33208. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33209. mass: parsedMesh.physicsMass,
  33210. friction: parsedMesh.physicsFriction,
  33211. restitution: parsedMesh.physicsRestitution
  33212. }, scene);
  33213. }
  33214. // Instances
  33215. if (parsedMesh.instances) {
  33216. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33217. var parsedInstance = parsedMesh.instances[index];
  33218. var instance = mesh.createInstance(parsedInstance.name);
  33219. if (parsedInstance.id) {
  33220. instance.id = parsedInstance.id;
  33221. }
  33222. if (BABYLON.Tags) {
  33223. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33224. }
  33225. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33226. if (parsedInstance.parentId) {
  33227. instance._waitingParentId = parsedInstance.parentId;
  33228. }
  33229. if (parsedInstance.rotationQuaternion) {
  33230. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33231. }
  33232. else if (parsedInstance.rotation) {
  33233. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33234. }
  33235. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33236. instance.checkCollisions = mesh.checkCollisions;
  33237. if (parsedMesh.animations) {
  33238. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33239. parsedAnimation = parsedMesh.animations[animationIndex];
  33240. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33241. }
  33242. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33243. if (parsedMesh.autoAnimate) {
  33244. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33245. }
  33246. }
  33247. }
  33248. }
  33249. return mesh;
  33250. };
  33251. /**
  33252. * Creates a ribbon mesh.
  33253. * Please consider using the same method from the MeshBuilder class instead.
  33254. * 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.
  33255. *
  33256. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33257. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33258. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33259. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33260. * 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.
  33261. * 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.
  33262. * 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
  33263. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33264. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33266. */
  33267. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33268. if (closeArray === void 0) { closeArray = false; }
  33269. if (updatable === void 0) { updatable = false; }
  33270. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33271. pathArray: pathArray,
  33272. closeArray: closeArray,
  33273. closePath: closePath,
  33274. offset: offset,
  33275. updatable: updatable,
  33276. sideOrientation: sideOrientation,
  33277. instance: instance
  33278. }, scene);
  33279. };
  33280. /**
  33281. * Creates a plane polygonal mesh. By default, this is a disc.
  33282. * Please consider using the same method from the MeshBuilder class instead.
  33283. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33284. * 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.
  33285. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33286. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33288. */
  33289. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33290. if (scene === void 0) { scene = null; }
  33291. var options = {
  33292. radius: radius,
  33293. tessellation: tessellation,
  33294. sideOrientation: sideOrientation,
  33295. updatable: updatable
  33296. };
  33297. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33298. };
  33299. /**
  33300. * Creates a box mesh.
  33301. * Please consider using the same method from the MeshBuilder class instead.
  33302. * The parameter `size` sets the size (float) of each box side (default 1).
  33303. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33304. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33306. */
  33307. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33308. if (scene === void 0) { scene = null; }
  33309. var options = {
  33310. size: size,
  33311. sideOrientation: sideOrientation,
  33312. updatable: updatable
  33313. };
  33314. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33315. };
  33316. /**
  33317. * Creates a sphere mesh.
  33318. * Please consider using the same method from the MeshBuilder class instead.
  33319. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33320. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33322. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33324. */
  33325. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33326. var options = {
  33327. segments: segments,
  33328. diameterX: diameter,
  33329. diameterY: diameter,
  33330. diameterZ: diameter,
  33331. sideOrientation: sideOrientation,
  33332. updatable: updatable
  33333. };
  33334. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33335. };
  33336. /**
  33337. * Creates a cylinder or a cone mesh.
  33338. * Please consider using the same method from the MeshBuilder class instead.
  33339. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33340. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33341. * 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.
  33342. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33343. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33344. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33345. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33346. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33347. */
  33348. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33349. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33350. if (scene !== undefined) {
  33351. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33352. updatable = scene;
  33353. }
  33354. scene = subdivisions;
  33355. subdivisions = 1;
  33356. }
  33357. var options = {
  33358. height: height,
  33359. diameterTop: diameterTop,
  33360. diameterBottom: diameterBottom,
  33361. tessellation: tessellation,
  33362. subdivisions: subdivisions,
  33363. sideOrientation: sideOrientation,
  33364. updatable: updatable
  33365. };
  33366. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33367. };
  33368. // Torus (Code from SharpDX.org)
  33369. /**
  33370. * Creates a torus mesh.
  33371. * Please consider using the same method from the MeshBuilder class instead.
  33372. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33373. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33374. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33375. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33376. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33378. */
  33379. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33380. var options = {
  33381. diameter: diameter,
  33382. thickness: thickness,
  33383. tessellation: tessellation,
  33384. sideOrientation: sideOrientation,
  33385. updatable: updatable
  33386. };
  33387. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33388. };
  33389. /**
  33390. * Creates a torus knot mesh.
  33391. * Please consider using the same method from the MeshBuilder class instead.
  33392. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33393. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33394. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33395. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33396. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33397. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33398. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33399. */
  33400. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33401. var options = {
  33402. radius: radius,
  33403. tube: tube,
  33404. radialSegments: radialSegments,
  33405. tubularSegments: tubularSegments,
  33406. p: p,
  33407. q: q,
  33408. sideOrientation: sideOrientation,
  33409. updatable: updatable
  33410. };
  33411. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33412. };
  33413. /**
  33414. * Creates a line mesh.
  33415. * Please consider using the same method from the MeshBuilder class instead.
  33416. * 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.
  33417. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33418. * The parameter `points` is an array successive Vector3.
  33419. * 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
  33420. * When updating an instance, remember that only point positions can change, not the number of points.
  33421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33422. */
  33423. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33424. if (scene === void 0) { scene = null; }
  33425. if (updatable === void 0) { updatable = false; }
  33426. if (instance === void 0) { instance = null; }
  33427. var options = {
  33428. points: points,
  33429. updatable: updatable,
  33430. instance: instance
  33431. };
  33432. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33433. };
  33434. /**
  33435. * Creates a dashed line mesh.
  33436. * Please consider using the same method from the MeshBuilder class instead.
  33437. * 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.
  33438. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33439. * The parameter `points` is an array successive Vector3.
  33440. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33441. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33442. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33443. * 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
  33444. * When updating an instance, remember that only point positions can change, not the number of points.
  33445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33446. */
  33447. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33448. if (scene === void 0) { scene = null; }
  33449. var options = {
  33450. points: points,
  33451. dashSize: dashSize,
  33452. gapSize: gapSize,
  33453. dashNb: dashNb,
  33454. updatable: updatable,
  33455. instance: instance
  33456. };
  33457. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33458. };
  33459. /**
  33460. * Creates a polygon mesh.
  33461. * Please consider using the same method from the MeshBuilder class instead.
  33462. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33463. * 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.
  33464. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33466. * Remember you can only change the shape positions, not their number when updating a polygon.
  33467. */
  33468. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33469. var options = {
  33470. shape: shape,
  33471. holes: holes,
  33472. updatable: updatable,
  33473. sideOrientation: sideOrientation
  33474. };
  33475. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33476. };
  33477. /**
  33478. * Creates an extruded polygon mesh, with depth in the Y direction.
  33479. * Please consider using the same method from the MeshBuilder class instead.
  33480. */
  33481. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33482. var options = {
  33483. shape: shape,
  33484. holes: holes,
  33485. depth: depth,
  33486. updatable: updatable,
  33487. sideOrientation: sideOrientation
  33488. };
  33489. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33490. };
  33491. /**
  33492. * Creates an extruded shape mesh.
  33493. * 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.
  33494. * Please consider using the same method from the MeshBuilder class instead.
  33495. *
  33496. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33497. * 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
  33498. * extruded along the Z axis.
  33499. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33500. * 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.
  33501. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33502. * 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
  33503. * 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
  33504. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33505. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33506. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33508. */
  33509. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33510. if (scene === void 0) { scene = null; }
  33511. var options = {
  33512. shape: shape,
  33513. path: path,
  33514. scale: scale,
  33515. rotation: rotation,
  33516. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33517. sideOrientation: sideOrientation,
  33518. instance: instance,
  33519. updatable: updatable
  33520. };
  33521. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33522. };
  33523. /**
  33524. * Creates an custom extruded shape mesh.
  33525. * 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.
  33526. * Please consider using the same method from the MeshBuilder class instead.
  33527. *
  33528. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33529. * 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
  33530. * extruded along the Z axis.
  33531. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33532. * 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
  33533. * and the distance of this point from the begining of the path :
  33534. * ```javascript
  33535. * var rotationFunction = function(i, distance) {
  33536. * // do things
  33537. * return rotationValue; }
  33538. * ```
  33539. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33540. * 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
  33541. * and the distance of this point from the begining of the path :
  33542. * ```javascript
  33543. * var scaleFunction = function(i, distance) {
  33544. * // do things
  33545. * return scaleValue;}
  33546. * ```
  33547. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33548. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33549. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33550. * 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
  33551. * 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
  33552. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33554. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33556. */
  33557. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33558. var options = {
  33559. shape: shape,
  33560. path: path,
  33561. scaleFunction: scaleFunction,
  33562. rotationFunction: rotationFunction,
  33563. ribbonCloseArray: ribbonCloseArray,
  33564. ribbonClosePath: ribbonClosePath,
  33565. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33566. sideOrientation: sideOrientation,
  33567. instance: instance,
  33568. updatable: updatable
  33569. };
  33570. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33571. };
  33572. /**
  33573. * Creates lathe mesh.
  33574. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33575. * Please consider using the same method from the MeshBuilder class instead.
  33576. * 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
  33577. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33578. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33579. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33581. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33583. */
  33584. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33585. var options = {
  33586. shape: shape,
  33587. radius: radius,
  33588. tessellation: tessellation,
  33589. sideOrientation: sideOrientation,
  33590. updatable: updatable
  33591. };
  33592. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33593. };
  33594. /**
  33595. * Creates a plane mesh.
  33596. * Please consider using the same method from the MeshBuilder class instead.
  33597. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33598. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33599. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33600. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33601. */
  33602. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33603. var options = {
  33604. size: size,
  33605. width: size,
  33606. height: size,
  33607. sideOrientation: sideOrientation,
  33608. updatable: updatable
  33609. };
  33610. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33611. };
  33612. /**
  33613. * Creates a ground mesh.
  33614. * Please consider using the same method from the MeshBuilder class instead.
  33615. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33616. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33618. */
  33619. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33620. var options = {
  33621. width: width,
  33622. height: height,
  33623. subdivisions: subdivisions,
  33624. updatable: updatable
  33625. };
  33626. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33627. };
  33628. /**
  33629. * Creates a tiled ground mesh.
  33630. * Please consider using the same method from the MeshBuilder class instead.
  33631. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33632. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33633. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33634. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33635. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33636. * numbers of subdivisions on the ground width and height of each tile.
  33637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33638. */
  33639. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33640. var options = {
  33641. xmin: xmin,
  33642. zmin: zmin,
  33643. xmax: xmax,
  33644. zmax: zmax,
  33645. subdivisions: subdivisions,
  33646. precision: precision,
  33647. updatable: updatable
  33648. };
  33649. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33650. };
  33651. /**
  33652. * Creates a ground mesh from a height map.
  33653. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33654. * Please consider using the same method from the MeshBuilder class instead.
  33655. * The parameter `url` sets the URL of the height map image resource.
  33656. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33657. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33658. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33659. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33660. * 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).
  33661. * This function is passed the newly built mesh :
  33662. * ```javascript
  33663. * function(mesh) { // do things
  33664. * return; }
  33665. * ```
  33666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33667. */
  33668. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33669. var options = {
  33670. width: width,
  33671. height: height,
  33672. subdivisions: subdivisions,
  33673. minHeight: minHeight,
  33674. maxHeight: maxHeight,
  33675. updatable: updatable,
  33676. onReady: onReady
  33677. };
  33678. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33679. };
  33680. /**
  33681. * Creates a tube mesh.
  33682. * 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.
  33683. * Please consider using the same method from the MeshBuilder class instead.
  33684. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33685. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33686. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33687. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33688. * 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.
  33689. * It must return a radius value (positive float) :
  33690. * ```javascript
  33691. * var radiusFunction = function(i, distance) {
  33692. * // do things
  33693. * return radius; }
  33694. * ```
  33695. * 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
  33696. * 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
  33697. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33698. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33699. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33700. */
  33701. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33702. var options = {
  33703. path: path,
  33704. radius: radius,
  33705. tessellation: tessellation,
  33706. radiusFunction: radiusFunction,
  33707. arc: 1,
  33708. cap: cap,
  33709. updatable: updatable,
  33710. sideOrientation: sideOrientation,
  33711. instance: instance
  33712. };
  33713. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33714. };
  33715. /**
  33716. * Creates a polyhedron mesh.
  33717. * Please consider using the same method from the MeshBuilder class instead.
  33718. * 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
  33719. * to choose the wanted type.
  33720. * The parameter `size` (positive float, default 1) sets the polygon size.
  33721. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33722. * 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`.
  33723. * 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
  33724. * 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)`).
  33725. * 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
  33726. * 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.
  33727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33728. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33730. */
  33731. Mesh.CreatePolyhedron = function (name, options, scene) {
  33732. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33733. };
  33734. /**
  33735. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33736. * Please consider using the same method from the MeshBuilder class instead.
  33737. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33738. * 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`).
  33739. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33740. * 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.
  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.CreateIcoSphere = function (name, options, scene) {
  33746. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33747. };
  33748. /**
  33749. * Creates a decal mesh.
  33750. * Please consider using the same method from the MeshBuilder class instead.
  33751. * 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.
  33752. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33753. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33754. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33755. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33756. */
  33757. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33758. var options = {
  33759. position: position,
  33760. normal: normal,
  33761. size: size,
  33762. angle: angle
  33763. };
  33764. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33765. };
  33766. // Skeletons
  33767. /**
  33768. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33769. */
  33770. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33771. if (!this._sourcePositions) {
  33772. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33773. if (!source) {
  33774. return this._sourcePositions;
  33775. }
  33776. this._sourcePositions = new Float32Array(source);
  33777. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33778. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33779. }
  33780. }
  33781. return this._sourcePositions;
  33782. };
  33783. /**
  33784. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33785. */
  33786. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33787. if (!this._sourceNormals) {
  33788. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33789. if (!source) {
  33790. return this._sourceNormals;
  33791. }
  33792. this._sourceNormals = new Float32Array(source);
  33793. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33794. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33795. }
  33796. }
  33797. return this._sourceNormals;
  33798. };
  33799. /**
  33800. * Updates the vertex buffer by applying transformation from the bones.
  33801. * Returns the Mesh.
  33802. *
  33803. * @param {skeleton} skeleton to apply
  33804. */
  33805. Mesh.prototype.applySkeleton = function (skeleton) {
  33806. if (!this.geometry) {
  33807. return this;
  33808. }
  33809. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33810. return this;
  33811. }
  33812. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33813. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33814. return this;
  33815. }
  33816. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33817. return this;
  33818. }
  33819. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33820. return this;
  33821. }
  33822. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33823. return this;
  33824. }
  33825. if (!this._sourcePositions) {
  33826. var submeshes = this.subMeshes.slice();
  33827. this.setPositionsForCPUSkinning();
  33828. this.subMeshes = submeshes;
  33829. }
  33830. if (!this._sourceNormals) {
  33831. this.setNormalsForCPUSkinning();
  33832. }
  33833. // positionsData checks for not being Float32Array will only pass at most once
  33834. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33835. if (!positionsData) {
  33836. return this;
  33837. }
  33838. if (!(positionsData instanceof Float32Array)) {
  33839. positionsData = new Float32Array(positionsData);
  33840. }
  33841. // normalsData checks for not being Float32Array will only pass at most once
  33842. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33843. if (!normalsData) {
  33844. return this;
  33845. }
  33846. if (!(normalsData instanceof Float32Array)) {
  33847. normalsData = new Float32Array(normalsData);
  33848. }
  33849. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33850. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33851. if (!matricesWeightsData || !matricesIndicesData) {
  33852. return this;
  33853. }
  33854. var needExtras = this.numBoneInfluencers > 4;
  33855. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33856. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33857. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33858. var tempVector3 = BABYLON.Vector3.Zero();
  33859. var finalMatrix = new BABYLON.Matrix();
  33860. var tempMatrix = new BABYLON.Matrix();
  33861. var matWeightIdx = 0;
  33862. var inf;
  33863. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33864. var weight;
  33865. for (inf = 0; inf < 4; inf++) {
  33866. weight = matricesWeightsData[matWeightIdx + inf];
  33867. if (weight > 0) {
  33868. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33869. finalMatrix.addToSelf(tempMatrix);
  33870. }
  33871. }
  33872. if (needExtras) {
  33873. for (inf = 0; inf < 4; inf++) {
  33874. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33875. if (weight > 0) {
  33876. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33877. finalMatrix.addToSelf(tempMatrix);
  33878. }
  33879. }
  33880. }
  33881. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33882. tempVector3.toArray(positionsData, index);
  33883. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33884. tempVector3.toArray(normalsData, index);
  33885. finalMatrix.reset();
  33886. }
  33887. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33888. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33889. return this;
  33890. };
  33891. // Tools
  33892. /**
  33893. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33894. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33895. */
  33896. Mesh.MinMax = function (meshes) {
  33897. var minVector = null;
  33898. var maxVector = null;
  33899. meshes.forEach(function (mesh, index, array) {
  33900. var boundingInfo = mesh.getBoundingInfo();
  33901. var boundingBox = boundingInfo.boundingBox;
  33902. if (!minVector || !maxVector) {
  33903. minVector = boundingBox.minimumWorld;
  33904. maxVector = boundingBox.maximumWorld;
  33905. }
  33906. else {
  33907. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33908. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33909. }
  33910. });
  33911. if (!minVector || !maxVector) {
  33912. return {
  33913. min: BABYLON.Vector3.Zero(),
  33914. max: BABYLON.Vector3.Zero()
  33915. };
  33916. }
  33917. return {
  33918. min: minVector,
  33919. max: maxVector
  33920. };
  33921. };
  33922. /**
  33923. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33924. */
  33925. Mesh.Center = function (meshesOrMinMaxVector) {
  33926. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33927. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33928. };
  33929. /**
  33930. * Merge the array of meshes into a single mesh for performance reasons.
  33931. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33932. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33933. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33934. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33935. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33936. */
  33937. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33938. if (disposeSource === void 0) { disposeSource = true; }
  33939. var index;
  33940. if (!allow32BitsIndices) {
  33941. var totalVertices = 0;
  33942. // Counting vertices
  33943. for (index = 0; index < meshes.length; index++) {
  33944. if (meshes[index]) {
  33945. totalVertices += meshes[index].getTotalVertices();
  33946. if (totalVertices > 65536) {
  33947. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33948. return null;
  33949. }
  33950. }
  33951. }
  33952. }
  33953. // Merge
  33954. var vertexData = null;
  33955. var otherVertexData;
  33956. var indiceArray = new Array();
  33957. var source = null;
  33958. for (index = 0; index < meshes.length; index++) {
  33959. if (meshes[index]) {
  33960. meshes[index].computeWorldMatrix(true);
  33961. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33962. otherVertexData.transform(meshes[index].getWorldMatrix());
  33963. if (vertexData) {
  33964. vertexData.merge(otherVertexData);
  33965. }
  33966. else {
  33967. vertexData = otherVertexData;
  33968. source = meshes[index];
  33969. }
  33970. if (subdivideWithSubMeshes) {
  33971. indiceArray.push(meshes[index].getTotalIndices());
  33972. }
  33973. }
  33974. }
  33975. source = source;
  33976. if (!meshSubclass) {
  33977. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33978. }
  33979. vertexData.applyToMesh(meshSubclass);
  33980. // Setting properties
  33981. meshSubclass.material = source.material;
  33982. meshSubclass.checkCollisions = source.checkCollisions;
  33983. // Cleaning
  33984. if (disposeSource) {
  33985. for (index = 0; index < meshes.length; index++) {
  33986. if (meshes[index]) {
  33987. meshes[index].dispose();
  33988. }
  33989. }
  33990. }
  33991. // Subdivide
  33992. if (subdivideWithSubMeshes) {
  33993. //-- removal of global submesh
  33994. meshSubclass.releaseSubMeshes();
  33995. index = 0;
  33996. var offset = 0;
  33997. //-- apply subdivision according to index table
  33998. while (index < indiceArray.length) {
  33999. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34000. offset += indiceArray[index];
  34001. index++;
  34002. }
  34003. }
  34004. return meshSubclass;
  34005. };
  34006. // Consts
  34007. Mesh._FRONTSIDE = 0;
  34008. Mesh._BACKSIDE = 1;
  34009. Mesh._DOUBLESIDE = 2;
  34010. Mesh._DEFAULTSIDE = 0;
  34011. Mesh._NO_CAP = 0;
  34012. Mesh._CAP_START = 1;
  34013. Mesh._CAP_END = 2;
  34014. Mesh._CAP_ALL = 3;
  34015. return Mesh;
  34016. }(BABYLON.AbstractMesh));
  34017. BABYLON.Mesh = Mesh;
  34018. })(BABYLON || (BABYLON = {}));
  34019. //# sourceMappingURL=babylon.mesh.js.map
  34020. var BABYLON;
  34021. (function (BABYLON) {
  34022. var BaseSubMesh = /** @class */ (function () {
  34023. function BaseSubMesh() {
  34024. }
  34025. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34026. get: function () {
  34027. return this._materialEffect;
  34028. },
  34029. enumerable: true,
  34030. configurable: true
  34031. });
  34032. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34033. if (defines === void 0) { defines = null; }
  34034. if (this._materialEffect === effect) {
  34035. if (!effect) {
  34036. this._materialDefines = null;
  34037. }
  34038. return;
  34039. }
  34040. this._materialDefines = defines;
  34041. this._materialEffect = effect;
  34042. };
  34043. return BaseSubMesh;
  34044. }());
  34045. BABYLON.BaseSubMesh = BaseSubMesh;
  34046. var SubMesh = /** @class */ (function (_super) {
  34047. __extends(SubMesh, _super);
  34048. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34049. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34050. var _this = _super.call(this) || this;
  34051. _this.materialIndex = materialIndex;
  34052. _this.verticesStart = verticesStart;
  34053. _this.verticesCount = verticesCount;
  34054. _this.indexStart = indexStart;
  34055. _this.indexCount = indexCount;
  34056. _this._renderId = 0;
  34057. _this._mesh = mesh;
  34058. _this._renderingMesh = renderingMesh || mesh;
  34059. mesh.subMeshes.push(_this);
  34060. _this._trianglePlanes = [];
  34061. _this._id = mesh.subMeshes.length - 1;
  34062. if (createBoundingBox) {
  34063. _this.refreshBoundingInfo();
  34064. mesh.computeWorldMatrix(true);
  34065. }
  34066. return _this;
  34067. }
  34068. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34069. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34070. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34071. };
  34072. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34073. get: function () {
  34074. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34075. },
  34076. enumerable: true,
  34077. configurable: true
  34078. });
  34079. /**
  34080. * Returns the submesh BoudingInfo object.
  34081. */
  34082. SubMesh.prototype.getBoundingInfo = function () {
  34083. if (this.IsGlobal) {
  34084. return this._mesh.getBoundingInfo();
  34085. }
  34086. return this._boundingInfo;
  34087. };
  34088. /**
  34089. * Sets the submesh BoundingInfo.
  34090. * Return the SubMesh.
  34091. */
  34092. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34093. this._boundingInfo = boundingInfo;
  34094. return this;
  34095. };
  34096. /**
  34097. * Returns the mesh of the current submesh.
  34098. */
  34099. SubMesh.prototype.getMesh = function () {
  34100. return this._mesh;
  34101. };
  34102. /**
  34103. * Returns the rendering mesh of the submesh.
  34104. */
  34105. SubMesh.prototype.getRenderingMesh = function () {
  34106. return this._renderingMesh;
  34107. };
  34108. /**
  34109. * Returns the submesh material.
  34110. */
  34111. SubMesh.prototype.getMaterial = function () {
  34112. var rootMaterial = this._renderingMesh.material;
  34113. if (rootMaterial === null || rootMaterial === undefined) {
  34114. return this._mesh.getScene().defaultMaterial;
  34115. }
  34116. else if (rootMaterial.getSubMaterial) {
  34117. var multiMaterial = rootMaterial;
  34118. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34119. if (this._currentMaterial !== effectiveMaterial) {
  34120. this._currentMaterial = effectiveMaterial;
  34121. this._materialDefines = null;
  34122. }
  34123. return effectiveMaterial;
  34124. }
  34125. return rootMaterial;
  34126. };
  34127. // Methods
  34128. /**
  34129. * Sets a new updated BoundingInfo object to the submesh.
  34130. * Returns the SubMesh.
  34131. */
  34132. SubMesh.prototype.refreshBoundingInfo = function () {
  34133. this._lastColliderWorldVertices = null;
  34134. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34135. return this;
  34136. }
  34137. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34138. if (!data) {
  34139. this._boundingInfo = this._mesh.getBoundingInfo();
  34140. return this;
  34141. }
  34142. var indices = this._renderingMesh.getIndices();
  34143. var extend;
  34144. //is this the only submesh?
  34145. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34146. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34147. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34148. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34149. }
  34150. else {
  34151. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34152. }
  34153. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34154. return this;
  34155. };
  34156. SubMesh.prototype._checkCollision = function (collider) {
  34157. var boundingInfo = this.getBoundingInfo();
  34158. return boundingInfo._checkCollision(collider);
  34159. };
  34160. /**
  34161. * Updates the submesh BoundingInfo.
  34162. * Returns the Submesh.
  34163. */
  34164. SubMesh.prototype.updateBoundingInfo = function (world) {
  34165. var boundingInfo = this.getBoundingInfo();
  34166. if (!boundingInfo) {
  34167. this.refreshBoundingInfo();
  34168. boundingInfo = this.getBoundingInfo();
  34169. }
  34170. boundingInfo.update(world);
  34171. return this;
  34172. };
  34173. /**
  34174. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34175. * Boolean returned.
  34176. */
  34177. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34178. var boundingInfo = this.getBoundingInfo();
  34179. if (!boundingInfo) {
  34180. return false;
  34181. }
  34182. return boundingInfo.isInFrustum(frustumPlanes);
  34183. };
  34184. /**
  34185. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34186. * Boolean returned.
  34187. */
  34188. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34189. var boundingInfo = this.getBoundingInfo();
  34190. if (!boundingInfo) {
  34191. return false;
  34192. }
  34193. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34194. };
  34195. /**
  34196. * Renders the submesh.
  34197. * Returns it.
  34198. */
  34199. SubMesh.prototype.render = function (enableAlphaMode) {
  34200. this._renderingMesh.render(this, enableAlphaMode);
  34201. return this;
  34202. };
  34203. /**
  34204. * Returns a new Index Buffer.
  34205. * Type returned : WebGLBuffer.
  34206. */
  34207. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34208. if (!this._linesIndexBuffer) {
  34209. var linesIndices = [];
  34210. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34211. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34212. }
  34213. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34214. this.linesIndexCount = linesIndices.length;
  34215. }
  34216. return this._linesIndexBuffer;
  34217. };
  34218. /**
  34219. * True is the passed Ray intersects the submesh bounding box.
  34220. * Boolean returned.
  34221. */
  34222. SubMesh.prototype.canIntersects = function (ray) {
  34223. var boundingInfo = this.getBoundingInfo();
  34224. if (!boundingInfo) {
  34225. return false;
  34226. }
  34227. return ray.intersectsBox(boundingInfo.boundingBox);
  34228. };
  34229. /**
  34230. * Returns an object IntersectionInfo.
  34231. */
  34232. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34233. var intersectInfo = null;
  34234. var material = this.getMaterial();
  34235. if (!material) {
  34236. return null;
  34237. }
  34238. switch (material.fillMode) {
  34239. case BABYLON.Material.PointListDrawMode:
  34240. case BABYLON.Material.LineListDrawMode:
  34241. case BABYLON.Material.LineLoopDrawMode:
  34242. case BABYLON.Material.LineStripDrawMode:
  34243. case BABYLON.Material.TriangleFanDrawMode:
  34244. case BABYLON.Material.TriangleStripDrawMode:
  34245. return null;
  34246. }
  34247. // LineMesh first as it's also a Mesh...
  34248. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34249. var lineMesh = this._mesh;
  34250. // Line test
  34251. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34252. var p0 = positions[indices[index]];
  34253. var p1 = positions[indices[index + 1]];
  34254. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34255. if (length < 0) {
  34256. continue;
  34257. }
  34258. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34259. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34260. if (fastCheck) {
  34261. break;
  34262. }
  34263. }
  34264. }
  34265. }
  34266. else {
  34267. // Triangles test
  34268. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34269. var p0 = positions[indices[index]];
  34270. var p1 = positions[indices[index + 1]];
  34271. var p2 = positions[indices[index + 2]];
  34272. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34273. if (currentIntersectInfo) {
  34274. if (currentIntersectInfo.distance < 0) {
  34275. continue;
  34276. }
  34277. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34278. intersectInfo = currentIntersectInfo;
  34279. intersectInfo.faceId = index / 3;
  34280. if (fastCheck) {
  34281. break;
  34282. }
  34283. }
  34284. }
  34285. }
  34286. }
  34287. return intersectInfo;
  34288. };
  34289. SubMesh.prototype._rebuild = function () {
  34290. if (this._linesIndexBuffer) {
  34291. this._linesIndexBuffer = null;
  34292. }
  34293. };
  34294. // Clone
  34295. /**
  34296. * Creates a new Submesh from the passed Mesh.
  34297. */
  34298. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34299. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34300. if (!this.IsGlobal) {
  34301. var boundingInfo = this.getBoundingInfo();
  34302. if (!boundingInfo) {
  34303. return result;
  34304. }
  34305. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34306. }
  34307. return result;
  34308. };
  34309. // Dispose
  34310. /**
  34311. * Disposes the Submesh.
  34312. * Returns nothing.
  34313. */
  34314. SubMesh.prototype.dispose = function () {
  34315. if (this._linesIndexBuffer) {
  34316. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34317. this._linesIndexBuffer = null;
  34318. }
  34319. // Remove from mesh
  34320. var index = this._mesh.subMeshes.indexOf(this);
  34321. this._mesh.subMeshes.splice(index, 1);
  34322. };
  34323. // Statics
  34324. /**
  34325. * Creates a new Submesh from the passed parameters :
  34326. * - materialIndex (integer) : the index of the main mesh material.
  34327. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34328. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34329. * - mesh (Mesh) : the main mesh to create the submesh from.
  34330. * - renderingMesh (optional Mesh) : rendering mesh.
  34331. */
  34332. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34333. var minVertexIndex = Number.MAX_VALUE;
  34334. var maxVertexIndex = -Number.MAX_VALUE;
  34335. renderingMesh = (renderingMesh || mesh);
  34336. var indices = renderingMesh.getIndices();
  34337. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34338. var vertexIndex = indices[index];
  34339. if (vertexIndex < minVertexIndex)
  34340. minVertexIndex = vertexIndex;
  34341. if (vertexIndex > maxVertexIndex)
  34342. maxVertexIndex = vertexIndex;
  34343. }
  34344. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34345. };
  34346. return SubMesh;
  34347. }(BaseSubMesh));
  34348. BABYLON.SubMesh = SubMesh;
  34349. })(BABYLON || (BABYLON = {}));
  34350. //# sourceMappingURL=babylon.subMesh.js.map
  34351. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34352. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34353. s = arguments[i];
  34354. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34355. t[p] = s[p];
  34356. }
  34357. return t;
  34358. };
  34359. var BABYLON;
  34360. (function (BABYLON) {
  34361. /**
  34362. * Manages the defines for the Material
  34363. */
  34364. var MaterialDefines = /** @class */ (function () {
  34365. function MaterialDefines() {
  34366. this._isDirty = true;
  34367. /** @hidden */
  34368. this._areLightsDirty = true;
  34369. /** @hidden */
  34370. this._areAttributesDirty = true;
  34371. /** @hidden */
  34372. this._areTexturesDirty = true;
  34373. /** @hidden */
  34374. this._areFresnelDirty = true;
  34375. /** @hidden */
  34376. this._areMiscDirty = true;
  34377. /** @hidden */
  34378. this._areImageProcessingDirty = true;
  34379. /** @hidden */
  34380. this._normals = false;
  34381. /** @hidden */
  34382. this._uvs = false;
  34383. /** @hidden */
  34384. this._needNormals = false;
  34385. /** @hidden */
  34386. this._needUVs = false;
  34387. }
  34388. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34389. /**
  34390. * Specifies if the material needs to be re-calculated
  34391. */
  34392. get: function () {
  34393. return this._isDirty;
  34394. },
  34395. enumerable: true,
  34396. configurable: true
  34397. });
  34398. /**
  34399. * Marks the material to indicate that it has been re-calculated
  34400. */
  34401. MaterialDefines.prototype.markAsProcessed = function () {
  34402. this._isDirty = false;
  34403. this._areAttributesDirty = false;
  34404. this._areTexturesDirty = false;
  34405. this._areFresnelDirty = false;
  34406. this._areLightsDirty = false;
  34407. this._areMiscDirty = false;
  34408. this._areImageProcessingDirty = false;
  34409. };
  34410. /**
  34411. * Marks the material to indicate that it needs to be re-calculated
  34412. */
  34413. MaterialDefines.prototype.markAsUnprocessed = function () {
  34414. this._isDirty = true;
  34415. };
  34416. /**
  34417. * Marks the material to indicate all of its defines need to be re-calculated
  34418. */
  34419. MaterialDefines.prototype.markAllAsDirty = function () {
  34420. this._areTexturesDirty = true;
  34421. this._areAttributesDirty = true;
  34422. this._areLightsDirty = true;
  34423. this._areFresnelDirty = true;
  34424. this._areMiscDirty = true;
  34425. this._areImageProcessingDirty = true;
  34426. this._isDirty = true;
  34427. };
  34428. /**
  34429. * Marks the material to indicate that image processing needs to be re-calculated
  34430. */
  34431. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34432. this._areImageProcessingDirty = true;
  34433. this._isDirty = true;
  34434. };
  34435. /**
  34436. * Marks the material to indicate the lights need to be re-calculated
  34437. */
  34438. MaterialDefines.prototype.markAsLightDirty = function () {
  34439. this._areLightsDirty = true;
  34440. this._isDirty = true;
  34441. };
  34442. /**
  34443. * Marks the attribute state as changed
  34444. */
  34445. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34446. this._areAttributesDirty = true;
  34447. this._isDirty = true;
  34448. };
  34449. /**
  34450. * Marks the texture state as changed
  34451. */
  34452. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34453. this._areTexturesDirty = true;
  34454. this._isDirty = true;
  34455. };
  34456. /**
  34457. * Marks the fresnel state as changed
  34458. */
  34459. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34460. this._areFresnelDirty = true;
  34461. this._isDirty = true;
  34462. };
  34463. /**
  34464. * Marks the misc state as changed
  34465. */
  34466. MaterialDefines.prototype.markAsMiscDirty = function () {
  34467. this._areMiscDirty = true;
  34468. this._isDirty = true;
  34469. };
  34470. /**
  34471. * Rebuilds the material defines
  34472. */
  34473. MaterialDefines.prototype.rebuild = function () {
  34474. if (this._keys) {
  34475. delete this._keys;
  34476. }
  34477. this._keys = [];
  34478. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34479. var key = _a[_i];
  34480. if (key[0] === "_") {
  34481. continue;
  34482. }
  34483. this._keys.push(key);
  34484. }
  34485. };
  34486. /**
  34487. * Specifies if two material defines are equal
  34488. * @param other - A material define instance to compare to
  34489. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34490. */
  34491. MaterialDefines.prototype.isEqual = function (other) {
  34492. if (this._keys.length !== other._keys.length) {
  34493. return false;
  34494. }
  34495. for (var index = 0; index < this._keys.length; index++) {
  34496. var prop = this._keys[index];
  34497. if (this[prop] !== other[prop]) {
  34498. return false;
  34499. }
  34500. }
  34501. return true;
  34502. };
  34503. /**
  34504. * Clones this instance's defines to another instance
  34505. * @param other - material defines to clone values to
  34506. */
  34507. MaterialDefines.prototype.cloneTo = function (other) {
  34508. if (this._keys.length !== other._keys.length) {
  34509. other._keys = this._keys.slice(0);
  34510. }
  34511. for (var index = 0; index < this._keys.length; index++) {
  34512. var prop = this._keys[index];
  34513. other[prop] = this[prop];
  34514. }
  34515. };
  34516. /**
  34517. * Resets the material define values
  34518. */
  34519. MaterialDefines.prototype.reset = function () {
  34520. for (var index = 0; index < this._keys.length; index++) {
  34521. var prop = this._keys[index];
  34522. var type = typeof this[prop];
  34523. switch (type) {
  34524. case "number":
  34525. this[prop] = 0;
  34526. break;
  34527. case "string":
  34528. this[prop] = "";
  34529. break;
  34530. default:
  34531. this[prop] = false;
  34532. break;
  34533. }
  34534. }
  34535. };
  34536. /**
  34537. * Converts the material define values to a string
  34538. * @returns - String of material define information
  34539. */
  34540. MaterialDefines.prototype.toString = function () {
  34541. var result = "";
  34542. for (var index = 0; index < this._keys.length; index++) {
  34543. var prop = this._keys[index];
  34544. var value = this[prop];
  34545. var type = typeof value;
  34546. switch (type) {
  34547. case "number":
  34548. case "string":
  34549. result += "#define " + prop + " " + value + "\n";
  34550. break;
  34551. default:
  34552. if (value) {
  34553. result += "#define " + prop + "\n";
  34554. }
  34555. break;
  34556. }
  34557. }
  34558. return result;
  34559. };
  34560. return MaterialDefines;
  34561. }());
  34562. BABYLON.MaterialDefines = MaterialDefines;
  34563. /**
  34564. * Base class for the main features of a material in Babylon.js
  34565. */
  34566. var Material = /** @class */ (function () {
  34567. /**
  34568. * Creates a material instance
  34569. * @param name defines the name of the material
  34570. * @param scene defines the scene to reference
  34571. * @param doNotAdd specifies if the material should be added to the scene
  34572. */
  34573. function Material(name, scene, doNotAdd) {
  34574. /**
  34575. * Specifies if the ready state should be checked on each call
  34576. */
  34577. this.checkReadyOnEveryCall = false;
  34578. /**
  34579. * Specifies if the ready state should be checked once
  34580. */
  34581. this.checkReadyOnlyOnce = false;
  34582. /**
  34583. * The state of the material
  34584. */
  34585. this.state = "";
  34586. /**
  34587. * The alpha value of the material
  34588. */
  34589. this._alpha = 1.0;
  34590. /**
  34591. * Specifies if back face culling is enabled
  34592. */
  34593. this._backFaceCulling = true;
  34594. /**
  34595. * Specifies if the material should be serialized
  34596. */
  34597. this.doNotSerialize = false;
  34598. /**
  34599. * Specifies if the effect should be stored on sub meshes
  34600. */
  34601. this.storeEffectOnSubMeshes = false;
  34602. /**
  34603. * An event triggered when the material is disposed
  34604. */
  34605. this.onDisposeObservable = new BABYLON.Observable();
  34606. /**
  34607. * Stores the value of the alpha mode
  34608. */
  34609. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34610. /**
  34611. * Stores the state of the need depth pre-pass value
  34612. */
  34613. this._needDepthPrePass = false;
  34614. /**
  34615. * Specifies if depth writing should be disabled
  34616. */
  34617. this.disableDepthWrite = false;
  34618. /**
  34619. * Specifies if depth writing should be forced
  34620. */
  34621. this.forceDepthWrite = false;
  34622. /**
  34623. * Specifies if there should be a separate pass for culling
  34624. */
  34625. this.separateCullingPass = false;
  34626. /**
  34627. * Stores the state specifing if fog should be enabled
  34628. */
  34629. this._fogEnabled = true;
  34630. /**
  34631. * Stores the size of points
  34632. */
  34633. this.pointSize = 1.0;
  34634. /**
  34635. * Stores the z offset value
  34636. */
  34637. this.zOffset = 0;
  34638. /**
  34639. * Specifies if the material was previously ready
  34640. */
  34641. this._wasPreviouslyReady = false;
  34642. /**
  34643. * Stores the fill mode state
  34644. */
  34645. this._fillMode = Material.TriangleFillMode;
  34646. this.name = name;
  34647. this.id = name || BABYLON.Tools.RandomId();
  34648. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34649. this.uniqueId = this._scene.getUniqueId();
  34650. if (this._scene.useRightHandedSystem) {
  34651. this.sideOrientation = Material.ClockWiseSideOrientation;
  34652. }
  34653. else {
  34654. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34655. }
  34656. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34657. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34658. if (!doNotAdd) {
  34659. this._scene.materials.push(this);
  34660. }
  34661. }
  34662. Object.defineProperty(Material, "TriangleFillMode", {
  34663. /**
  34664. * Returns the triangle fill mode
  34665. */
  34666. get: function () {
  34667. return Material._TriangleFillMode;
  34668. },
  34669. enumerable: true,
  34670. configurable: true
  34671. });
  34672. Object.defineProperty(Material, "WireFrameFillMode", {
  34673. /**
  34674. * Returns the wireframe mode
  34675. */
  34676. get: function () {
  34677. return Material._WireFrameFillMode;
  34678. },
  34679. enumerable: true,
  34680. configurable: true
  34681. });
  34682. Object.defineProperty(Material, "PointFillMode", {
  34683. /**
  34684. * Returns the point fill mode
  34685. */
  34686. get: function () {
  34687. return Material._PointFillMode;
  34688. },
  34689. enumerable: true,
  34690. configurable: true
  34691. });
  34692. Object.defineProperty(Material, "PointListDrawMode", {
  34693. /**
  34694. * Returns the point list draw mode
  34695. */
  34696. get: function () {
  34697. return Material._PointListDrawMode;
  34698. },
  34699. enumerable: true,
  34700. configurable: true
  34701. });
  34702. Object.defineProperty(Material, "LineListDrawMode", {
  34703. /**
  34704. * Returns the line list draw mode
  34705. */
  34706. get: function () {
  34707. return Material._LineListDrawMode;
  34708. },
  34709. enumerable: true,
  34710. configurable: true
  34711. });
  34712. Object.defineProperty(Material, "LineLoopDrawMode", {
  34713. /**
  34714. * Returns the line loop draw mode
  34715. */
  34716. get: function () {
  34717. return Material._LineLoopDrawMode;
  34718. },
  34719. enumerable: true,
  34720. configurable: true
  34721. });
  34722. Object.defineProperty(Material, "LineStripDrawMode", {
  34723. /**
  34724. * Returns the line strip draw mode
  34725. */
  34726. get: function () {
  34727. return Material._LineStripDrawMode;
  34728. },
  34729. enumerable: true,
  34730. configurable: true
  34731. });
  34732. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34733. /**
  34734. * Returns the triangle strip draw mode
  34735. */
  34736. get: function () {
  34737. return Material._TriangleStripDrawMode;
  34738. },
  34739. enumerable: true,
  34740. configurable: true
  34741. });
  34742. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34743. /**
  34744. * Returns the triangle fan draw mode
  34745. */
  34746. get: function () {
  34747. return Material._TriangleFanDrawMode;
  34748. },
  34749. enumerable: true,
  34750. configurable: true
  34751. });
  34752. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34753. /**
  34754. * Returns the clock-wise side orientation
  34755. */
  34756. get: function () {
  34757. return Material._ClockWiseSideOrientation;
  34758. },
  34759. enumerable: true,
  34760. configurable: true
  34761. });
  34762. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34763. /**
  34764. * Returns the counter clock-wise side orientation
  34765. */
  34766. get: function () {
  34767. return Material._CounterClockWiseSideOrientation;
  34768. },
  34769. enumerable: true,
  34770. configurable: true
  34771. });
  34772. Object.defineProperty(Material, "TextureDirtyFlag", {
  34773. /**
  34774. * Returns the dirty texture flag value
  34775. */
  34776. get: function () {
  34777. return Material._TextureDirtyFlag;
  34778. },
  34779. enumerable: true,
  34780. configurable: true
  34781. });
  34782. Object.defineProperty(Material, "LightDirtyFlag", {
  34783. /**
  34784. * Returns the dirty light flag value
  34785. */
  34786. get: function () {
  34787. return Material._LightDirtyFlag;
  34788. },
  34789. enumerable: true,
  34790. configurable: true
  34791. });
  34792. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34793. /**
  34794. * Returns the dirty fresnel flag value
  34795. */
  34796. get: function () {
  34797. return Material._FresnelDirtyFlag;
  34798. },
  34799. enumerable: true,
  34800. configurable: true
  34801. });
  34802. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34803. /**
  34804. * Returns the dirty attributes flag value
  34805. */
  34806. get: function () {
  34807. return Material._AttributesDirtyFlag;
  34808. },
  34809. enumerable: true,
  34810. configurable: true
  34811. });
  34812. Object.defineProperty(Material, "MiscDirtyFlag", {
  34813. /**
  34814. * Returns the dirty misc flag value
  34815. */
  34816. get: function () {
  34817. return Material._MiscDirtyFlag;
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. Object.defineProperty(Material.prototype, "alpha", {
  34823. /**
  34824. * Gets the alpha value of the material
  34825. */
  34826. get: function () {
  34827. return this._alpha;
  34828. },
  34829. /**
  34830. * Sets the alpha value of the material
  34831. */
  34832. set: function (value) {
  34833. if (this._alpha === value) {
  34834. return;
  34835. }
  34836. this._alpha = value;
  34837. this.markAsDirty(Material.MiscDirtyFlag);
  34838. },
  34839. enumerable: true,
  34840. configurable: true
  34841. });
  34842. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34843. /**
  34844. * Gets the back-face culling state
  34845. */
  34846. get: function () {
  34847. return this._backFaceCulling;
  34848. },
  34849. /**
  34850. * Sets the back-face culling state
  34851. */
  34852. set: function (value) {
  34853. if (this._backFaceCulling === value) {
  34854. return;
  34855. }
  34856. this._backFaceCulling = value;
  34857. this.markAsDirty(Material.TextureDirtyFlag);
  34858. },
  34859. enumerable: true,
  34860. configurable: true
  34861. });
  34862. Object.defineProperty(Material.prototype, "onDispose", {
  34863. /**
  34864. * Called during a dispose event
  34865. */
  34866. set: function (callback) {
  34867. if (this._onDisposeObserver) {
  34868. this.onDisposeObservable.remove(this._onDisposeObserver);
  34869. }
  34870. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. Object.defineProperty(Material.prototype, "onBindObservable", {
  34876. /**
  34877. * An event triggered when the material is bound
  34878. */
  34879. get: function () {
  34880. if (!this._onBindObservable) {
  34881. this._onBindObservable = new BABYLON.Observable();
  34882. }
  34883. return this._onBindObservable;
  34884. },
  34885. enumerable: true,
  34886. configurable: true
  34887. });
  34888. Object.defineProperty(Material.prototype, "onBind", {
  34889. /**
  34890. * Called during a bind event
  34891. */
  34892. set: function (callback) {
  34893. if (this._onBindObserver) {
  34894. this.onBindObservable.remove(this._onBindObserver);
  34895. }
  34896. this._onBindObserver = this.onBindObservable.add(callback);
  34897. },
  34898. enumerable: true,
  34899. configurable: true
  34900. });
  34901. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34902. /**
  34903. * An event triggered when the material is unbound
  34904. */
  34905. get: function () {
  34906. if (!this._onUnBindObservable) {
  34907. this._onUnBindObservable = new BABYLON.Observable();
  34908. }
  34909. return this._onUnBindObservable;
  34910. },
  34911. enumerable: true,
  34912. configurable: true
  34913. });
  34914. Object.defineProperty(Material.prototype, "alphaMode", {
  34915. /**
  34916. * Gets the value of the alpha mode
  34917. */
  34918. get: function () {
  34919. return this._alphaMode;
  34920. },
  34921. /**
  34922. * Sets the value of the alpha mode.
  34923. *
  34924. * | Value | Type | Description |
  34925. * | --- | --- | --- |
  34926. * | 0 | ALPHA_DISABLE | |
  34927. * | 1 | ALPHA_ADD | |
  34928. * | 2 | ALPHA_COMBINE | |
  34929. * | 3 | ALPHA_SUBTRACT | |
  34930. * | 4 | ALPHA_MULTIPLY | |
  34931. * | 5 | ALPHA_MAXIMIZED | |
  34932. * | 6 | ALPHA_ONEONE | |
  34933. * | 7 | ALPHA_PREMULTIPLIED | |
  34934. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34935. * | 9 | ALPHA_INTERPOLATE | |
  34936. * | 10 | ALPHA_SCREENMODE | |
  34937. *
  34938. */
  34939. set: function (value) {
  34940. if (this._alphaMode === value) {
  34941. return;
  34942. }
  34943. this._alphaMode = value;
  34944. this.markAsDirty(Material.TextureDirtyFlag);
  34945. },
  34946. enumerable: true,
  34947. configurable: true
  34948. });
  34949. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34950. /**
  34951. * Gets the depth pre-pass value
  34952. */
  34953. get: function () {
  34954. return this._needDepthPrePass;
  34955. },
  34956. /**
  34957. * Sets the need depth pre-pass value
  34958. */
  34959. set: function (value) {
  34960. if (this._needDepthPrePass === value) {
  34961. return;
  34962. }
  34963. this._needDepthPrePass = value;
  34964. if (this._needDepthPrePass) {
  34965. this.checkReadyOnEveryCall = true;
  34966. }
  34967. },
  34968. enumerable: true,
  34969. configurable: true
  34970. });
  34971. Object.defineProperty(Material.prototype, "fogEnabled", {
  34972. /**
  34973. * Gets the value of the fog enabled state
  34974. */
  34975. get: function () {
  34976. return this._fogEnabled;
  34977. },
  34978. /**
  34979. * Sets the state for enabling fog
  34980. */
  34981. set: function (value) {
  34982. if (this._fogEnabled === value) {
  34983. return;
  34984. }
  34985. this._fogEnabled = value;
  34986. this.markAsDirty(Material.MiscDirtyFlag);
  34987. },
  34988. enumerable: true,
  34989. configurable: true
  34990. });
  34991. Object.defineProperty(Material.prototype, "wireframe", {
  34992. /**
  34993. * Gets a value specifying if wireframe mode is enabled
  34994. */
  34995. get: function () {
  34996. switch (this._fillMode) {
  34997. case Material.WireFrameFillMode:
  34998. case Material.LineListDrawMode:
  34999. case Material.LineLoopDrawMode:
  35000. case Material.LineStripDrawMode:
  35001. return true;
  35002. }
  35003. return this._scene.forceWireframe;
  35004. },
  35005. /**
  35006. * Sets the state of wireframe mode
  35007. */
  35008. set: function (value) {
  35009. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35010. },
  35011. enumerable: true,
  35012. configurable: true
  35013. });
  35014. Object.defineProperty(Material.prototype, "pointsCloud", {
  35015. /**
  35016. * Gets the value specifying if point clouds are enabled
  35017. */
  35018. get: function () {
  35019. switch (this._fillMode) {
  35020. case Material.PointFillMode:
  35021. case Material.PointListDrawMode:
  35022. return true;
  35023. }
  35024. return this._scene.forcePointsCloud;
  35025. },
  35026. /**
  35027. * Sets the state of point cloud mode
  35028. */
  35029. set: function (value) {
  35030. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35031. },
  35032. enumerable: true,
  35033. configurable: true
  35034. });
  35035. Object.defineProperty(Material.prototype, "fillMode", {
  35036. /**
  35037. * Gets the material fill mode
  35038. */
  35039. get: function () {
  35040. return this._fillMode;
  35041. },
  35042. /**
  35043. * Sets the material fill mode
  35044. */
  35045. set: function (value) {
  35046. if (this._fillMode === value) {
  35047. return;
  35048. }
  35049. this._fillMode = value;
  35050. this.markAsDirty(Material.MiscDirtyFlag);
  35051. },
  35052. enumerable: true,
  35053. configurable: true
  35054. });
  35055. /**
  35056. * Returns a string representation of the current material
  35057. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35058. * @returns a string with material information
  35059. */
  35060. Material.prototype.toString = function (fullDetails) {
  35061. var ret = "Name: " + this.name;
  35062. if (fullDetails) {
  35063. }
  35064. return ret;
  35065. };
  35066. /**
  35067. * Gets the class name of the material
  35068. * @returns a string with the class name of the material
  35069. */
  35070. Material.prototype.getClassName = function () {
  35071. return "Material";
  35072. };
  35073. Object.defineProperty(Material.prototype, "isFrozen", {
  35074. /**
  35075. * Specifies if updates for the material been locked
  35076. */
  35077. get: function () {
  35078. return this.checkReadyOnlyOnce;
  35079. },
  35080. enumerable: true,
  35081. configurable: true
  35082. });
  35083. /**
  35084. * Locks updates for the material
  35085. */
  35086. Material.prototype.freeze = function () {
  35087. this.checkReadyOnlyOnce = true;
  35088. };
  35089. /**
  35090. * Unlocks updates for the material
  35091. */
  35092. Material.prototype.unfreeze = function () {
  35093. this.checkReadyOnlyOnce = false;
  35094. };
  35095. /**
  35096. * Specifies if the material is ready to be used
  35097. * @param mesh defines the mesh to check
  35098. * @param useInstances specifies if instances should be used
  35099. * @returns a boolean indicating if the material is ready to be used
  35100. */
  35101. Material.prototype.isReady = function (mesh, useInstances) {
  35102. return true;
  35103. };
  35104. /**
  35105. * Specifies that the submesh is ready to be used
  35106. * @param mesh defines the mesh to check
  35107. * @param subMesh defines which submesh to check
  35108. * @param useInstances specifies that instances should be used
  35109. * @returns a boolean indicating that the submesh is ready or not
  35110. */
  35111. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35112. return false;
  35113. };
  35114. /**
  35115. * Returns the material effect
  35116. * @returns the effect associated with the material
  35117. */
  35118. Material.prototype.getEffect = function () {
  35119. return this._effect;
  35120. };
  35121. /**
  35122. * Returns the current scene
  35123. * @returns a Scene
  35124. */
  35125. Material.prototype.getScene = function () {
  35126. return this._scene;
  35127. };
  35128. /**
  35129. * Specifies if the material will require alpha blending
  35130. * @returns a boolean specifying if alpha blending is needed
  35131. */
  35132. Material.prototype.needAlphaBlending = function () {
  35133. return (this.alpha < 1.0);
  35134. };
  35135. /**
  35136. * Specifies if the mesh will require alpha blending
  35137. * @param mesh defines the mesh to check
  35138. * @returns a boolean specifying if alpha blending is needed for the mesh
  35139. */
  35140. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35141. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35142. };
  35143. /**
  35144. * Specifies if this material should be rendered in alpha test mode
  35145. * @returns a boolean specifying if an alpha test is needed.
  35146. */
  35147. Material.prototype.needAlphaTesting = function () {
  35148. return false;
  35149. };
  35150. /**
  35151. * Gets the texture used for the alpha test
  35152. * @returns the texture to use for alpha testing
  35153. */
  35154. Material.prototype.getAlphaTestTexture = function () {
  35155. return null;
  35156. };
  35157. /**
  35158. * Marks the material to indicate that it needs to be re-calculated
  35159. */
  35160. Material.prototype.markDirty = function () {
  35161. this._wasPreviouslyReady = false;
  35162. };
  35163. /** @hidden */
  35164. Material.prototype._preBind = function (effect, overrideOrientation) {
  35165. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35166. var engine = this._scene.getEngine();
  35167. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35168. var reverse = orientation === Material.ClockWiseSideOrientation;
  35169. engine.enableEffect(effect ? effect : this._effect);
  35170. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35171. return reverse;
  35172. };
  35173. /**
  35174. * Binds the material to the mesh
  35175. * @param world defines the world transformation matrix
  35176. * @param mesh defines the mesh to bind the material to
  35177. */
  35178. Material.prototype.bind = function (world, mesh) {
  35179. };
  35180. /**
  35181. * Binds the submesh to the material
  35182. * @param world defines the world transformation matrix
  35183. * @param mesh defines the mesh containing the submesh
  35184. * @param subMesh defines the submesh to bind the material to
  35185. */
  35186. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35187. };
  35188. /**
  35189. * Binds the world matrix to the material
  35190. * @param world defines the world transformation matrix
  35191. */
  35192. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35193. };
  35194. /**
  35195. * Binds the scene's uniform buffer to the effect.
  35196. * @param effect defines the effect to bind to the scene uniform buffer
  35197. * @param sceneUbo defines the uniform buffer storing scene data
  35198. */
  35199. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35200. sceneUbo.bindToEffect(effect, "Scene");
  35201. };
  35202. /**
  35203. * Binds the view matrix to the effect
  35204. * @param effect defines the effect to bind the view matrix to
  35205. */
  35206. Material.prototype.bindView = function (effect) {
  35207. if (!this._useUBO) {
  35208. effect.setMatrix("view", this.getScene().getViewMatrix());
  35209. }
  35210. else {
  35211. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35212. }
  35213. };
  35214. /**
  35215. * Binds the view projection matrix to the effect
  35216. * @param effect defines the effect to bind the view projection matrix to
  35217. */
  35218. Material.prototype.bindViewProjection = function (effect) {
  35219. if (!this._useUBO) {
  35220. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35221. }
  35222. else {
  35223. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35224. }
  35225. };
  35226. /**
  35227. * Specifies if material alpha testing should be turned on for the mesh
  35228. * @param mesh defines the mesh to check
  35229. */
  35230. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35231. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35232. };
  35233. /**
  35234. * Processes to execute after binding the material to a mesh
  35235. * @param mesh defines the rendered mesh
  35236. */
  35237. Material.prototype._afterBind = function (mesh) {
  35238. this._scene._cachedMaterial = this;
  35239. if (mesh) {
  35240. this._scene._cachedVisibility = mesh.visibility;
  35241. }
  35242. else {
  35243. this._scene._cachedVisibility = 1;
  35244. }
  35245. if (this._onBindObservable && mesh) {
  35246. this._onBindObservable.notifyObservers(mesh);
  35247. }
  35248. if (this.disableDepthWrite) {
  35249. var engine = this._scene.getEngine();
  35250. this._cachedDepthWriteState = engine.getDepthWrite();
  35251. engine.setDepthWrite(false);
  35252. }
  35253. };
  35254. /**
  35255. * Unbinds the material from the mesh
  35256. */
  35257. Material.prototype.unbind = function () {
  35258. if (this._onUnBindObservable) {
  35259. this._onUnBindObservable.notifyObservers(this);
  35260. }
  35261. if (this.disableDepthWrite) {
  35262. var engine = this._scene.getEngine();
  35263. engine.setDepthWrite(this._cachedDepthWriteState);
  35264. }
  35265. };
  35266. /**
  35267. * Gets the active textures from the material
  35268. * @returns an array of textures
  35269. */
  35270. Material.prototype.getActiveTextures = function () {
  35271. return [];
  35272. };
  35273. /**
  35274. * Specifies if the material uses a texture
  35275. * @param texture defines the texture to check against the material
  35276. * @returns a boolean specifying if the material uses the texture
  35277. */
  35278. Material.prototype.hasTexture = function (texture) {
  35279. return false;
  35280. };
  35281. /**
  35282. * Makes a duplicate of the material, and gives it a new name
  35283. * @param name defines the new name for the duplicated material
  35284. * @returns the cloned material
  35285. */
  35286. Material.prototype.clone = function (name) {
  35287. return null;
  35288. };
  35289. /**
  35290. * Gets the meshes bound to the material
  35291. * @returns an array of meshes bound to the material
  35292. */
  35293. Material.prototype.getBindedMeshes = function () {
  35294. var result = new Array();
  35295. for (var index = 0; index < this._scene.meshes.length; index++) {
  35296. var mesh = this._scene.meshes[index];
  35297. if (mesh.material === this) {
  35298. result.push(mesh);
  35299. }
  35300. }
  35301. return result;
  35302. };
  35303. /**
  35304. * Force shader compilation
  35305. * @param mesh defines the mesh associated with this material
  35306. * @param onCompiled defines a function to execute once the material is compiled
  35307. * @param options defines the options to configure the compilation
  35308. */
  35309. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35310. var _this = this;
  35311. var localOptions = __assign({ clipPlane: false }, options);
  35312. var subMesh = new BABYLON.BaseSubMesh();
  35313. var scene = this.getScene();
  35314. var checkReady = function () {
  35315. if (!_this._scene || !_this._scene.getEngine()) {
  35316. return;
  35317. }
  35318. if (subMesh._materialDefines) {
  35319. subMesh._materialDefines._renderId = -1;
  35320. }
  35321. var clipPlaneState = scene.clipPlane;
  35322. if (localOptions.clipPlane) {
  35323. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35324. }
  35325. if (_this.storeEffectOnSubMeshes) {
  35326. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35327. if (onCompiled) {
  35328. onCompiled(_this);
  35329. }
  35330. }
  35331. else {
  35332. setTimeout(checkReady, 16);
  35333. }
  35334. }
  35335. else {
  35336. if (_this.isReady(mesh)) {
  35337. if (onCompiled) {
  35338. onCompiled(_this);
  35339. }
  35340. }
  35341. else {
  35342. setTimeout(checkReady, 16);
  35343. }
  35344. }
  35345. if (localOptions.clipPlane) {
  35346. scene.clipPlane = clipPlaneState;
  35347. }
  35348. };
  35349. checkReady();
  35350. };
  35351. /**
  35352. * Force shader compilation
  35353. * @param mesh defines the mesh that will use this material
  35354. * @param options defines additional options for compiling the shaders
  35355. * @returns a promise that resolves when the compilation completes
  35356. */
  35357. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35358. var _this = this;
  35359. return new Promise(function (resolve) {
  35360. _this.forceCompilation(mesh, function () {
  35361. resolve();
  35362. }, options);
  35363. });
  35364. };
  35365. /**
  35366. * Marks a define in the material to indicate that it needs to be re-computed
  35367. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35368. */
  35369. Material.prototype.markAsDirty = function (flag) {
  35370. if (flag & Material.TextureDirtyFlag) {
  35371. this._markAllSubMeshesAsTexturesDirty();
  35372. }
  35373. if (flag & Material.LightDirtyFlag) {
  35374. this._markAllSubMeshesAsLightsDirty();
  35375. }
  35376. if (flag & Material.FresnelDirtyFlag) {
  35377. this._markAllSubMeshesAsFresnelDirty();
  35378. }
  35379. if (flag & Material.AttributesDirtyFlag) {
  35380. this._markAllSubMeshesAsAttributesDirty();
  35381. }
  35382. if (flag & Material.MiscDirtyFlag) {
  35383. this._markAllSubMeshesAsMiscDirty();
  35384. }
  35385. this.getScene().resetCachedMaterial();
  35386. };
  35387. /**
  35388. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35389. * @param func defines a function which checks material defines against the submeshes
  35390. */
  35391. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35392. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35393. var mesh = _a[_i];
  35394. if (!mesh.subMeshes) {
  35395. continue;
  35396. }
  35397. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35398. var subMesh = _c[_b];
  35399. if (subMesh.getMaterial() !== this) {
  35400. continue;
  35401. }
  35402. if (!subMesh._materialDefines) {
  35403. continue;
  35404. }
  35405. func(subMesh._materialDefines);
  35406. }
  35407. }
  35408. };
  35409. /**
  35410. * Indicates that image processing needs to be re-calculated for all submeshes
  35411. */
  35412. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35413. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35414. };
  35415. /**
  35416. * Indicates that textures need to be re-calculated for all submeshes
  35417. */
  35418. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35419. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35420. };
  35421. /**
  35422. * Indicates that fresnel needs to be re-calculated for all submeshes
  35423. */
  35424. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35425. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35426. };
  35427. /**
  35428. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35429. */
  35430. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35431. this._markAllSubMeshesAsDirty(function (defines) {
  35432. defines.markAsFresnelDirty();
  35433. defines.markAsMiscDirty();
  35434. });
  35435. };
  35436. /**
  35437. * Indicates that lights need to be re-calculated for all submeshes
  35438. */
  35439. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35440. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35441. };
  35442. /**
  35443. * Indicates that attributes need to be re-calculated for all submeshes
  35444. */
  35445. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35446. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35447. };
  35448. /**
  35449. * Indicates that misc needs to be re-calculated for all submeshes
  35450. */
  35451. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35452. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35453. };
  35454. /**
  35455. * Indicates that textures and misc need to be re-calculated for all submeshes
  35456. */
  35457. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35458. this._markAllSubMeshesAsDirty(function (defines) {
  35459. defines.markAsTexturesDirty();
  35460. defines.markAsMiscDirty();
  35461. });
  35462. };
  35463. /**
  35464. * Disposes the material
  35465. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35466. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35467. */
  35468. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35469. // Animations
  35470. this.getScene().stopAnimation(this);
  35471. this.getScene().freeProcessedMaterials();
  35472. // Remove from scene
  35473. var index = this._scene.materials.indexOf(this);
  35474. if (index >= 0) {
  35475. this._scene.materials.splice(index, 1);
  35476. }
  35477. // Remove from meshes
  35478. for (index = 0; index < this._scene.meshes.length; index++) {
  35479. var mesh = this._scene.meshes[index];
  35480. if (mesh.material === this) {
  35481. mesh.material = null;
  35482. if (mesh.geometry) {
  35483. var geometry = (mesh.geometry);
  35484. if (this.storeEffectOnSubMeshes) {
  35485. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35486. var subMesh = _a[_i];
  35487. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35488. if (forceDisposeEffect && subMesh._materialEffect) {
  35489. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35490. }
  35491. }
  35492. }
  35493. else {
  35494. geometry._releaseVertexArrayObject(this._effect);
  35495. }
  35496. }
  35497. }
  35498. }
  35499. this._uniformBuffer.dispose();
  35500. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35501. if (forceDisposeEffect && this._effect) {
  35502. if (!this.storeEffectOnSubMeshes) {
  35503. this._scene.getEngine()._releaseEffect(this._effect);
  35504. }
  35505. this._effect = null;
  35506. }
  35507. // Callback
  35508. this.onDisposeObservable.notifyObservers(this);
  35509. this.onDisposeObservable.clear();
  35510. if (this._onBindObservable) {
  35511. this._onBindObservable.clear();
  35512. }
  35513. if (this._onUnBindObservable) {
  35514. this._onUnBindObservable.clear();
  35515. }
  35516. };
  35517. /**
  35518. * Serializes this material
  35519. * @returns the serialized material object
  35520. */
  35521. Material.prototype.serialize = function () {
  35522. return BABYLON.SerializationHelper.Serialize(this);
  35523. };
  35524. /**
  35525. * Creates a MultiMaterial from parsed MultiMaterial data.
  35526. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35527. * @param scene defines the hosting scene
  35528. * @returns a new MultiMaterial
  35529. */
  35530. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35531. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35532. multiMaterial.id = parsedMultiMaterial.id;
  35533. if (BABYLON.Tags) {
  35534. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35535. }
  35536. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35537. var subMatId = parsedMultiMaterial.materials[matIndex];
  35538. if (subMatId) {
  35539. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35540. }
  35541. else {
  35542. multiMaterial.subMaterials.push(null);
  35543. }
  35544. }
  35545. return multiMaterial;
  35546. };
  35547. /**
  35548. * Creates a material from parsed material data
  35549. * @param parsedMaterial defines parsed material data
  35550. * @param scene defines the hosting scene
  35551. * @param rootUrl defines the root URL to use to load textures
  35552. * @returns a new material
  35553. */
  35554. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35555. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35556. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35557. }
  35558. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35559. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35560. if (!BABYLON.LegacyPBRMaterial) {
  35561. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35562. return;
  35563. }
  35564. }
  35565. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35566. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35567. };
  35568. // Triangle views
  35569. Material._TriangleFillMode = 0;
  35570. Material._WireFrameFillMode = 1;
  35571. Material._PointFillMode = 2;
  35572. // Draw modes
  35573. Material._PointListDrawMode = 3;
  35574. Material._LineListDrawMode = 4;
  35575. Material._LineLoopDrawMode = 5;
  35576. Material._LineStripDrawMode = 6;
  35577. Material._TriangleStripDrawMode = 7;
  35578. Material._TriangleFanDrawMode = 8;
  35579. /**
  35580. * Stores the clock-wise side orientation
  35581. */
  35582. Material._ClockWiseSideOrientation = 0;
  35583. /**
  35584. * Stores the counter clock-wise side orientation
  35585. */
  35586. Material._CounterClockWiseSideOrientation = 1;
  35587. /**
  35588. * The dirty texture flag value
  35589. */
  35590. Material._TextureDirtyFlag = 1;
  35591. /**
  35592. * The dirty light flag value
  35593. */
  35594. Material._LightDirtyFlag = 2;
  35595. /**
  35596. * The dirty fresnel flag value
  35597. */
  35598. Material._FresnelDirtyFlag = 4;
  35599. /**
  35600. * The dirty attribute flag value
  35601. */
  35602. Material._AttributesDirtyFlag = 8;
  35603. /**
  35604. * The dirty misc flag value
  35605. */
  35606. Material._MiscDirtyFlag = 16;
  35607. __decorate([
  35608. BABYLON.serialize()
  35609. ], Material.prototype, "id", void 0);
  35610. __decorate([
  35611. BABYLON.serialize()
  35612. ], Material.prototype, "uniqueId", void 0);
  35613. __decorate([
  35614. BABYLON.serialize()
  35615. ], Material.prototype, "name", void 0);
  35616. __decorate([
  35617. BABYLON.serialize()
  35618. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35619. __decorate([
  35620. BABYLON.serialize()
  35621. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35622. __decorate([
  35623. BABYLON.serialize()
  35624. ], Material.prototype, "state", void 0);
  35625. __decorate([
  35626. BABYLON.serialize("alpha")
  35627. ], Material.prototype, "_alpha", void 0);
  35628. __decorate([
  35629. BABYLON.serialize("backFaceCulling")
  35630. ], Material.prototype, "_backFaceCulling", void 0);
  35631. __decorate([
  35632. BABYLON.serialize()
  35633. ], Material.prototype, "sideOrientation", void 0);
  35634. __decorate([
  35635. BABYLON.serialize("alphaMode")
  35636. ], Material.prototype, "_alphaMode", void 0);
  35637. __decorate([
  35638. BABYLON.serialize()
  35639. ], Material.prototype, "_needDepthPrePass", void 0);
  35640. __decorate([
  35641. BABYLON.serialize()
  35642. ], Material.prototype, "disableDepthWrite", void 0);
  35643. __decorate([
  35644. BABYLON.serialize()
  35645. ], Material.prototype, "forceDepthWrite", void 0);
  35646. __decorate([
  35647. BABYLON.serialize()
  35648. ], Material.prototype, "separateCullingPass", void 0);
  35649. __decorate([
  35650. BABYLON.serialize("fogEnabled")
  35651. ], Material.prototype, "_fogEnabled", void 0);
  35652. __decorate([
  35653. BABYLON.serialize()
  35654. ], Material.prototype, "pointSize", void 0);
  35655. __decorate([
  35656. BABYLON.serialize()
  35657. ], Material.prototype, "zOffset", void 0);
  35658. __decorate([
  35659. BABYLON.serialize()
  35660. ], Material.prototype, "wireframe", null);
  35661. __decorate([
  35662. BABYLON.serialize()
  35663. ], Material.prototype, "pointsCloud", null);
  35664. __decorate([
  35665. BABYLON.serialize()
  35666. ], Material.prototype, "fillMode", null);
  35667. return Material;
  35668. }());
  35669. BABYLON.Material = Material;
  35670. })(BABYLON || (BABYLON = {}));
  35671. //# sourceMappingURL=babylon.material.js.map
  35672. var BABYLON;
  35673. (function (BABYLON) {
  35674. var UniformBuffer = /** @class */ (function () {
  35675. /**
  35676. * Uniform buffer objects.
  35677. *
  35678. * Handles blocks of uniform on the GPU.
  35679. *
  35680. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35681. *
  35682. * For more information, please refer to :
  35683. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35684. */
  35685. function UniformBuffer(engine, data, dynamic) {
  35686. this._engine = engine;
  35687. this._noUBO = !engine.supportsUniformBuffers;
  35688. this._dynamic = dynamic;
  35689. this._data = data || [];
  35690. this._uniformLocations = {};
  35691. this._uniformSizes = {};
  35692. this._uniformLocationPointer = 0;
  35693. this._needSync = false;
  35694. if (this._noUBO) {
  35695. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35696. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35697. this.updateFloat = this._updateFloatForEffect;
  35698. this.updateFloat2 = this._updateFloat2ForEffect;
  35699. this.updateFloat3 = this._updateFloat3ForEffect;
  35700. this.updateFloat4 = this._updateFloat4ForEffect;
  35701. this.updateMatrix = this._updateMatrixForEffect;
  35702. this.updateVector3 = this._updateVector3ForEffect;
  35703. this.updateVector4 = this._updateVector4ForEffect;
  35704. this.updateColor3 = this._updateColor3ForEffect;
  35705. this.updateColor4 = this._updateColor4ForEffect;
  35706. }
  35707. else {
  35708. this._engine._uniformBuffers.push(this);
  35709. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35710. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35711. this.updateFloat = this._updateFloatForUniform;
  35712. this.updateFloat2 = this._updateFloat2ForUniform;
  35713. this.updateFloat3 = this._updateFloat3ForUniform;
  35714. this.updateFloat4 = this._updateFloat4ForUniform;
  35715. this.updateMatrix = this._updateMatrixForUniform;
  35716. this.updateVector3 = this._updateVector3ForUniform;
  35717. this.updateVector4 = this._updateVector4ForUniform;
  35718. this.updateColor3 = this._updateColor3ForUniform;
  35719. this.updateColor4 = this._updateColor4ForUniform;
  35720. }
  35721. }
  35722. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35723. // Properties
  35724. /**
  35725. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35726. * or just falling back on setUniformXXX calls.
  35727. */
  35728. get: function () {
  35729. return !this._noUBO;
  35730. },
  35731. enumerable: true,
  35732. configurable: true
  35733. });
  35734. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35735. /**
  35736. * Indicates if the WebGL underlying uniform buffer is in sync
  35737. * with the javascript cache data.
  35738. */
  35739. get: function () {
  35740. return !this._needSync;
  35741. },
  35742. enumerable: true,
  35743. configurable: true
  35744. });
  35745. /**
  35746. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35747. * Also, a dynamic UniformBuffer will disable cache verification and always
  35748. * update the underlying WebGL uniform buffer to the GPU.
  35749. */
  35750. UniformBuffer.prototype.isDynamic = function () {
  35751. return this._dynamic !== undefined;
  35752. };
  35753. /**
  35754. * The data cache on JS side.
  35755. */
  35756. UniformBuffer.prototype.getData = function () {
  35757. return this._bufferData;
  35758. };
  35759. /**
  35760. * The underlying WebGL Uniform buffer.
  35761. */
  35762. UniformBuffer.prototype.getBuffer = function () {
  35763. return this._buffer;
  35764. };
  35765. /**
  35766. * std140 layout specifies how to align data within an UBO structure.
  35767. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35768. * for specs.
  35769. */
  35770. UniformBuffer.prototype._fillAlignment = function (size) {
  35771. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35772. // and 4x4 matrices
  35773. // TODO : change if other types are used
  35774. var alignment;
  35775. if (size <= 2) {
  35776. alignment = size;
  35777. }
  35778. else {
  35779. alignment = 4;
  35780. }
  35781. if ((this._uniformLocationPointer % alignment) !== 0) {
  35782. var oldPointer = this._uniformLocationPointer;
  35783. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35784. var diff = this._uniformLocationPointer - oldPointer;
  35785. for (var i = 0; i < diff; i++) {
  35786. this._data.push(0);
  35787. }
  35788. }
  35789. };
  35790. /**
  35791. * Adds an uniform in the buffer.
  35792. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35793. * for the layout to be correct !
  35794. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35795. * @param {number|number[]} size Data size, or data directly.
  35796. */
  35797. UniformBuffer.prototype.addUniform = function (name, size) {
  35798. if (this._noUBO) {
  35799. return;
  35800. }
  35801. if (this._uniformLocations[name] !== undefined) {
  35802. // Already existing uniform
  35803. return;
  35804. }
  35805. // This function must be called in the order of the shader layout !
  35806. // size can be the size of the uniform, or data directly
  35807. var data;
  35808. if (size instanceof Array) {
  35809. data = size;
  35810. size = data.length;
  35811. }
  35812. else {
  35813. size = size;
  35814. data = [];
  35815. // Fill with zeros
  35816. for (var i = 0; i < size; i++) {
  35817. data.push(0);
  35818. }
  35819. }
  35820. this._fillAlignment(size);
  35821. this._uniformSizes[name] = size;
  35822. this._uniformLocations[name] = this._uniformLocationPointer;
  35823. this._uniformLocationPointer += size;
  35824. for (var i = 0; i < size; i++) {
  35825. this._data.push(data[i]);
  35826. }
  35827. this._needSync = true;
  35828. };
  35829. /**
  35830. * Wrapper for addUniform.
  35831. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35832. * @param {Matrix} mat A 4x4 matrix.
  35833. */
  35834. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35835. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35836. };
  35837. /**
  35838. * Wrapper for addUniform.
  35839. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35840. * @param {number} x
  35841. * @param {number} y
  35842. */
  35843. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35844. var temp = [x, y];
  35845. this.addUniform(name, temp);
  35846. };
  35847. /**
  35848. * Wrapper for addUniform.
  35849. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35850. * @param {number} x
  35851. * @param {number} y
  35852. * @param {number} z
  35853. */
  35854. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35855. var temp = [x, y, z];
  35856. this.addUniform(name, temp);
  35857. };
  35858. /**
  35859. * Wrapper for addUniform.
  35860. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35861. * @param {Color3} color
  35862. */
  35863. UniformBuffer.prototype.addColor3 = function (name, color) {
  35864. var temp = new Array();
  35865. color.toArray(temp);
  35866. this.addUniform(name, temp);
  35867. };
  35868. /**
  35869. * Wrapper for addUniform.
  35870. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35871. * @param {Color3} color
  35872. * @param {number} alpha
  35873. */
  35874. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35875. var temp = new Array();
  35876. color.toArray(temp);
  35877. temp.push(alpha);
  35878. this.addUniform(name, temp);
  35879. };
  35880. /**
  35881. * Wrapper for addUniform.
  35882. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35883. * @param {Vector3} vector
  35884. */
  35885. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35886. var temp = new Array();
  35887. vector.toArray(temp);
  35888. this.addUniform(name, temp);
  35889. };
  35890. /**
  35891. * Wrapper for addUniform.
  35892. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35893. */
  35894. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35895. this.addUniform(name, 12);
  35896. };
  35897. /**
  35898. * Wrapper for addUniform.
  35899. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35900. */
  35901. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35902. this.addUniform(name, 8);
  35903. };
  35904. /**
  35905. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35906. */
  35907. UniformBuffer.prototype.create = function () {
  35908. if (this._noUBO) {
  35909. return;
  35910. }
  35911. if (this._buffer) {
  35912. return; // nothing to do
  35913. }
  35914. // See spec, alignment must be filled as a vec4
  35915. this._fillAlignment(4);
  35916. this._bufferData = new Float32Array(this._data);
  35917. this._rebuild();
  35918. this._needSync = true;
  35919. };
  35920. UniformBuffer.prototype._rebuild = function () {
  35921. if (this._noUBO) {
  35922. return;
  35923. }
  35924. if (this._dynamic) {
  35925. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35926. }
  35927. else {
  35928. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35929. }
  35930. };
  35931. /**
  35932. * Updates the WebGL Uniform Buffer on the GPU.
  35933. * If the `dynamic` flag is set to true, no cache comparison is done.
  35934. * Otherwise, the buffer will be updated only if the cache differs.
  35935. */
  35936. UniformBuffer.prototype.update = function () {
  35937. if (!this._buffer) {
  35938. this.create();
  35939. return;
  35940. }
  35941. if (!this._dynamic && !this._needSync) {
  35942. return;
  35943. }
  35944. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35945. this._needSync = false;
  35946. };
  35947. /**
  35948. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35949. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35950. * @param {number[]|Float32Array} data Flattened data
  35951. * @param {number} size Size of the data.
  35952. */
  35953. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35954. var location = this._uniformLocations[uniformName];
  35955. if (location === undefined) {
  35956. if (this._buffer) {
  35957. // Cannot add an uniform if the buffer is already created
  35958. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35959. return;
  35960. }
  35961. this.addUniform(uniformName, size);
  35962. location = this._uniformLocations[uniformName];
  35963. }
  35964. if (!this._buffer) {
  35965. this.create();
  35966. }
  35967. if (!this._dynamic) {
  35968. // Cache for static uniform buffers
  35969. var changed = false;
  35970. for (var i = 0; i < size; i++) {
  35971. if (this._bufferData[location + i] !== data[i]) {
  35972. changed = true;
  35973. this._bufferData[location + i] = data[i];
  35974. }
  35975. }
  35976. this._needSync = this._needSync || changed;
  35977. }
  35978. else {
  35979. // No cache for dynamic
  35980. for (var i = 0; i < size; i++) {
  35981. this._bufferData[location + i] = data[i];
  35982. }
  35983. }
  35984. };
  35985. // Update methods
  35986. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35987. // To match std140, matrix must be realigned
  35988. for (var i = 0; i < 3; i++) {
  35989. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35990. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35991. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35992. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35993. }
  35994. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35995. };
  35996. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35997. this._currentEffect.setMatrix3x3(name, matrix);
  35998. };
  35999. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36000. this._currentEffect.setMatrix2x2(name, matrix);
  36001. };
  36002. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36003. // To match std140, matrix must be realigned
  36004. for (var i = 0; i < 2; i++) {
  36005. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36006. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36007. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36008. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36009. }
  36010. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36011. };
  36012. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36013. this._currentEffect.setFloat(name, x);
  36014. };
  36015. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36016. UniformBuffer._tempBuffer[0] = x;
  36017. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36018. };
  36019. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36020. if (suffix === void 0) { suffix = ""; }
  36021. this._currentEffect.setFloat2(name + suffix, x, y);
  36022. };
  36023. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36024. if (suffix === void 0) { suffix = ""; }
  36025. UniformBuffer._tempBuffer[0] = x;
  36026. UniformBuffer._tempBuffer[1] = y;
  36027. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36028. };
  36029. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36030. if (suffix === void 0) { suffix = ""; }
  36031. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36032. };
  36033. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36034. if (suffix === void 0) { suffix = ""; }
  36035. UniformBuffer._tempBuffer[0] = x;
  36036. UniformBuffer._tempBuffer[1] = y;
  36037. UniformBuffer._tempBuffer[2] = z;
  36038. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36039. };
  36040. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36041. if (suffix === void 0) { suffix = ""; }
  36042. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36043. };
  36044. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36045. if (suffix === void 0) { suffix = ""; }
  36046. UniformBuffer._tempBuffer[0] = x;
  36047. UniformBuffer._tempBuffer[1] = y;
  36048. UniformBuffer._tempBuffer[2] = z;
  36049. UniformBuffer._tempBuffer[3] = w;
  36050. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36051. };
  36052. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36053. this._currentEffect.setMatrix(name, mat);
  36054. };
  36055. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36056. this.updateUniform(name, mat.toArray(), 16);
  36057. };
  36058. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36059. this._currentEffect.setVector3(name, vector);
  36060. };
  36061. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36062. vector.toArray(UniformBuffer._tempBuffer);
  36063. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36064. };
  36065. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36066. this._currentEffect.setVector4(name, vector);
  36067. };
  36068. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36069. vector.toArray(UniformBuffer._tempBuffer);
  36070. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36071. };
  36072. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36073. if (suffix === void 0) { suffix = ""; }
  36074. this._currentEffect.setColor3(name + suffix, color);
  36075. };
  36076. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36077. if (suffix === void 0) { suffix = ""; }
  36078. color.toArray(UniformBuffer._tempBuffer);
  36079. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36080. };
  36081. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36082. if (suffix === void 0) { suffix = ""; }
  36083. this._currentEffect.setColor4(name + suffix, color, alpha);
  36084. };
  36085. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36086. if (suffix === void 0) { suffix = ""; }
  36087. color.toArray(UniformBuffer._tempBuffer);
  36088. UniformBuffer._tempBuffer[3] = alpha;
  36089. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36090. };
  36091. /**
  36092. * Sets a sampler uniform on the effect.
  36093. * @param {string} name Name of the sampler.
  36094. * @param {Texture} texture
  36095. */
  36096. UniformBuffer.prototype.setTexture = function (name, texture) {
  36097. this._currentEffect.setTexture(name, texture);
  36098. };
  36099. /**
  36100. * Directly updates the value of the uniform in the cache AND on the GPU.
  36101. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36102. * @param {number[]|Float32Array} data Flattened data
  36103. */
  36104. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36105. this.updateUniform(uniformName, data, data.length);
  36106. this.update();
  36107. };
  36108. /**
  36109. * Binds this uniform buffer to an effect.
  36110. * @param {Effect} effect
  36111. * @param {string} name Name of the uniform block in the shader.
  36112. */
  36113. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36114. this._currentEffect = effect;
  36115. if (this._noUBO || !this._buffer) {
  36116. return;
  36117. }
  36118. effect.bindUniformBuffer(this._buffer, name);
  36119. };
  36120. /**
  36121. * Disposes the uniform buffer.
  36122. */
  36123. UniformBuffer.prototype.dispose = function () {
  36124. if (this._noUBO) {
  36125. return;
  36126. }
  36127. var index = this._engine._uniformBuffers.indexOf(this);
  36128. if (index !== -1) {
  36129. this._engine._uniformBuffers.splice(index, 1);
  36130. }
  36131. if (!this._buffer) {
  36132. return;
  36133. }
  36134. if (this._engine._releaseBuffer(this._buffer)) {
  36135. this._buffer = null;
  36136. }
  36137. };
  36138. // Pool for avoiding memory leaks
  36139. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36140. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36141. return UniformBuffer;
  36142. }());
  36143. BABYLON.UniformBuffer = UniformBuffer;
  36144. })(BABYLON || (BABYLON = {}));
  36145. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36146. var BABYLON;
  36147. (function (BABYLON) {
  36148. /**
  36149. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36150. */
  36151. var VertexData = /** @class */ (function () {
  36152. function VertexData() {
  36153. }
  36154. /**
  36155. * Uses the passed data array to set the set the values for the specified kind of data
  36156. * @param data a linear array of floating numbers
  36157. * @param kind the type of data that is being set, eg positions, colors etc
  36158. */
  36159. VertexData.prototype.set = function (data, kind) {
  36160. switch (kind) {
  36161. case BABYLON.VertexBuffer.PositionKind:
  36162. this.positions = data;
  36163. break;
  36164. case BABYLON.VertexBuffer.NormalKind:
  36165. this.normals = data;
  36166. break;
  36167. case BABYLON.VertexBuffer.TangentKind:
  36168. this.tangents = data;
  36169. break;
  36170. case BABYLON.VertexBuffer.UVKind:
  36171. this.uvs = data;
  36172. break;
  36173. case BABYLON.VertexBuffer.UV2Kind:
  36174. this.uvs2 = data;
  36175. break;
  36176. case BABYLON.VertexBuffer.UV3Kind:
  36177. this.uvs3 = data;
  36178. break;
  36179. case BABYLON.VertexBuffer.UV4Kind:
  36180. this.uvs4 = data;
  36181. break;
  36182. case BABYLON.VertexBuffer.UV5Kind:
  36183. this.uvs5 = data;
  36184. break;
  36185. case BABYLON.VertexBuffer.UV6Kind:
  36186. this.uvs6 = data;
  36187. break;
  36188. case BABYLON.VertexBuffer.ColorKind:
  36189. this.colors = data;
  36190. break;
  36191. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36192. this.matricesIndices = data;
  36193. break;
  36194. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36195. this.matricesWeights = data;
  36196. break;
  36197. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36198. this.matricesIndicesExtra = data;
  36199. break;
  36200. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36201. this.matricesWeightsExtra = data;
  36202. break;
  36203. }
  36204. };
  36205. /**
  36206. * Associates the vertexData to the passed Mesh.
  36207. * Sets it as updatable or not (default `false`)
  36208. * @param mesh the mesh the vertexData is applied to
  36209. * @param updatable when used and having the value true allows new data to update the vertexData
  36210. * @returns the VertexData
  36211. */
  36212. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36213. this._applyTo(mesh, updatable);
  36214. return this;
  36215. };
  36216. /**
  36217. * Associates the vertexData to the passed Geometry.
  36218. * Sets it as updatable or not (default `false`)
  36219. * @param geometry the geometry the vertexData is applied to
  36220. * @param updatable when used and having the value true allows new data to update the vertexData
  36221. * @returns VertexData
  36222. */
  36223. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36224. this._applyTo(geometry, updatable);
  36225. return this;
  36226. };
  36227. /**
  36228. * Updates the associated mesh
  36229. * @param mesh the mesh to be updated
  36230. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36231. * @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
  36232. * @returns VertexData
  36233. */
  36234. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36235. this._update(mesh);
  36236. return this;
  36237. };
  36238. /**
  36239. * Updates the associated geometry
  36240. * @param geometry the geometry to be updated
  36241. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36242. * @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
  36243. * @returns VertexData.
  36244. */
  36245. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36246. this._update(geometry);
  36247. return this;
  36248. };
  36249. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36250. if (updatable === void 0) { updatable = false; }
  36251. if (this.positions) {
  36252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36253. }
  36254. if (this.normals) {
  36255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36256. }
  36257. if (this.tangents) {
  36258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36259. }
  36260. if (this.uvs) {
  36261. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36262. }
  36263. if (this.uvs2) {
  36264. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36265. }
  36266. if (this.uvs3) {
  36267. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36268. }
  36269. if (this.uvs4) {
  36270. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36271. }
  36272. if (this.uvs5) {
  36273. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36274. }
  36275. if (this.uvs6) {
  36276. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36277. }
  36278. if (this.colors) {
  36279. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36280. }
  36281. if (this.matricesIndices) {
  36282. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36283. }
  36284. if (this.matricesWeights) {
  36285. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36286. }
  36287. if (this.matricesIndicesExtra) {
  36288. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36289. }
  36290. if (this.matricesWeightsExtra) {
  36291. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36292. }
  36293. if (this.indices) {
  36294. meshOrGeometry.setIndices(this.indices, null, updatable);
  36295. }
  36296. else {
  36297. meshOrGeometry.setIndices([], null);
  36298. }
  36299. return this;
  36300. };
  36301. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36302. if (this.positions) {
  36303. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36304. }
  36305. if (this.normals) {
  36306. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36307. }
  36308. if (this.tangents) {
  36309. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36310. }
  36311. if (this.uvs) {
  36312. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36313. }
  36314. if (this.uvs2) {
  36315. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36316. }
  36317. if (this.uvs3) {
  36318. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36319. }
  36320. if (this.uvs4) {
  36321. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36322. }
  36323. if (this.uvs5) {
  36324. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36325. }
  36326. if (this.uvs6) {
  36327. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36328. }
  36329. if (this.colors) {
  36330. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36331. }
  36332. if (this.matricesIndices) {
  36333. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36334. }
  36335. if (this.matricesWeights) {
  36336. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36337. }
  36338. if (this.matricesIndicesExtra) {
  36339. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36340. }
  36341. if (this.matricesWeightsExtra) {
  36342. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36343. }
  36344. if (this.indices) {
  36345. meshOrGeometry.setIndices(this.indices, null);
  36346. }
  36347. return this;
  36348. };
  36349. /**
  36350. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36351. * @param matrix the transforming matrix
  36352. * @returns the VertexData
  36353. */
  36354. VertexData.prototype.transform = function (matrix) {
  36355. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36356. var transformed = BABYLON.Vector3.Zero();
  36357. var index;
  36358. if (this.positions) {
  36359. var position = BABYLON.Vector3.Zero();
  36360. for (index = 0; index < this.positions.length; index += 3) {
  36361. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36362. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36363. this.positions[index] = transformed.x;
  36364. this.positions[index + 1] = transformed.y;
  36365. this.positions[index + 2] = transformed.z;
  36366. }
  36367. }
  36368. if (this.normals) {
  36369. var normal = BABYLON.Vector3.Zero();
  36370. for (index = 0; index < this.normals.length; index += 3) {
  36371. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36372. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36373. this.normals[index] = transformed.x;
  36374. this.normals[index + 1] = transformed.y;
  36375. this.normals[index + 2] = transformed.z;
  36376. }
  36377. }
  36378. if (this.tangents) {
  36379. var tangent = BABYLON.Vector4.Zero();
  36380. var tangentTransformed = BABYLON.Vector4.Zero();
  36381. for (index = 0; index < this.tangents.length; index += 4) {
  36382. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36383. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36384. this.tangents[index] = tangentTransformed.x;
  36385. this.tangents[index + 1] = tangentTransformed.y;
  36386. this.tangents[index + 2] = tangentTransformed.z;
  36387. this.tangents[index + 3] = tangentTransformed.w;
  36388. }
  36389. }
  36390. if (flip && this.indices) {
  36391. for (index = 0; index < this.indices.length; index += 3) {
  36392. var tmp = this.indices[index + 1];
  36393. this.indices[index + 1] = this.indices[index + 2];
  36394. this.indices[index + 2] = tmp;
  36395. }
  36396. }
  36397. return this;
  36398. };
  36399. /**
  36400. * Merges the passed VertexData into the current one
  36401. * @param other the VertexData to be merged into the current one
  36402. * @returns the modified VertexData
  36403. */
  36404. VertexData.prototype.merge = function (other) {
  36405. this._validate();
  36406. other._validate();
  36407. if (!this.normals !== !other.normals ||
  36408. !this.tangents !== !other.tangents ||
  36409. !this.uvs !== !other.uvs ||
  36410. !this.uvs2 !== !other.uvs2 ||
  36411. !this.uvs3 !== !other.uvs3 ||
  36412. !this.uvs4 !== !other.uvs4 ||
  36413. !this.uvs5 !== !other.uvs5 ||
  36414. !this.uvs6 !== !other.uvs6 ||
  36415. !this.colors !== !other.colors ||
  36416. !this.matricesIndices !== !other.matricesIndices ||
  36417. !this.matricesWeights !== !other.matricesWeights ||
  36418. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36419. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36420. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36421. }
  36422. if (other.indices) {
  36423. if (!this.indices) {
  36424. this.indices = [];
  36425. }
  36426. var offset = this.positions ? this.positions.length / 3 : 0;
  36427. for (var index = 0; index < other.indices.length; index++) {
  36428. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36429. this.indices.push(other.indices[index] + offset);
  36430. }
  36431. }
  36432. this.positions = this._mergeElement(this.positions, other.positions);
  36433. this.normals = this._mergeElement(this.normals, other.normals);
  36434. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36435. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36436. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36437. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36438. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36439. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36440. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36441. this.colors = this._mergeElement(this.colors, other.colors);
  36442. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36443. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36444. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36445. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36446. return this;
  36447. };
  36448. VertexData.prototype._mergeElement = function (source, other) {
  36449. if (!source) {
  36450. return other;
  36451. }
  36452. if (!other) {
  36453. return source;
  36454. }
  36455. var len = other.length + source.length;
  36456. var isSrcTypedArray = source instanceof Float32Array;
  36457. var isOthTypedArray = other instanceof Float32Array;
  36458. // use non-loop method when the source is Float32Array
  36459. if (isSrcTypedArray) {
  36460. var ret32 = new Float32Array(len);
  36461. ret32.set(source);
  36462. ret32.set(other, source.length);
  36463. return ret32;
  36464. // source is number[], when other is also use concat
  36465. }
  36466. else if (!isOthTypedArray) {
  36467. return source.concat(other);
  36468. // source is a number[], but other is a Float32Array, loop required
  36469. }
  36470. else {
  36471. var ret = source.slice(0); // copy source to a separate array
  36472. for (var i = 0, len = other.length; i < len; i++) {
  36473. ret.push(other[i]);
  36474. }
  36475. return ret;
  36476. }
  36477. };
  36478. VertexData.prototype._validate = function () {
  36479. if (!this.positions) {
  36480. throw new Error("Positions are required");
  36481. }
  36482. var getElementCount = function (kind, values) {
  36483. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36484. if ((values.length % stride) !== 0) {
  36485. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36486. }
  36487. return values.length / stride;
  36488. };
  36489. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36490. var validateElementCount = function (kind, values) {
  36491. var elementCount = getElementCount(kind, values);
  36492. if (elementCount !== positionsElementCount) {
  36493. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36494. }
  36495. };
  36496. if (this.normals)
  36497. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36498. if (this.tangents)
  36499. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36500. if (this.uvs)
  36501. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36502. if (this.uvs2)
  36503. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36504. if (this.uvs3)
  36505. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36506. if (this.uvs4)
  36507. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36508. if (this.uvs5)
  36509. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36510. if (this.uvs6)
  36511. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36512. if (this.colors)
  36513. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36514. if (this.matricesIndices)
  36515. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36516. if (this.matricesWeights)
  36517. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36518. if (this.matricesIndicesExtra)
  36519. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36520. if (this.matricesWeightsExtra)
  36521. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36522. };
  36523. /**
  36524. * Serializes the VertexData
  36525. * @returns a serialized object
  36526. */
  36527. VertexData.prototype.serialize = function () {
  36528. var serializationObject = this.serialize();
  36529. if (this.positions) {
  36530. serializationObject.positions = this.positions;
  36531. }
  36532. if (this.normals) {
  36533. serializationObject.normals = this.normals;
  36534. }
  36535. if (this.tangents) {
  36536. serializationObject.tangents = this.tangents;
  36537. }
  36538. if (this.uvs) {
  36539. serializationObject.uvs = this.uvs;
  36540. }
  36541. if (this.uvs2) {
  36542. serializationObject.uvs2 = this.uvs2;
  36543. }
  36544. if (this.uvs3) {
  36545. serializationObject.uvs3 = this.uvs3;
  36546. }
  36547. if (this.uvs4) {
  36548. serializationObject.uvs4 = this.uvs4;
  36549. }
  36550. if (this.uvs5) {
  36551. serializationObject.uvs5 = this.uvs5;
  36552. }
  36553. if (this.uvs6) {
  36554. serializationObject.uvs6 = this.uvs6;
  36555. }
  36556. if (this.colors) {
  36557. serializationObject.colors = this.colors;
  36558. }
  36559. if (this.matricesIndices) {
  36560. serializationObject.matricesIndices = this.matricesIndices;
  36561. serializationObject.matricesIndices._isExpanded = true;
  36562. }
  36563. if (this.matricesWeights) {
  36564. serializationObject.matricesWeights = this.matricesWeights;
  36565. }
  36566. if (this.matricesIndicesExtra) {
  36567. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36568. serializationObject.matricesIndicesExtra._isExpanded = true;
  36569. }
  36570. if (this.matricesWeightsExtra) {
  36571. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36572. }
  36573. serializationObject.indices = this.indices;
  36574. return serializationObject;
  36575. };
  36576. // Statics
  36577. /**
  36578. * Extracts the vertexData from a mesh
  36579. * @param mesh the mesh from which to extract the VertexData
  36580. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36581. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36582. * @returns the object VertexData associated to the passed mesh
  36583. */
  36584. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36585. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36586. };
  36587. /**
  36588. * Extracts the vertexData from the geometry
  36589. * @param geometry the geometry from which to extract the VertexData
  36590. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36591. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36592. * @returns the object VertexData associated to the passed mesh
  36593. */
  36594. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36595. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36596. };
  36597. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36598. var result = new VertexData();
  36599. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36600. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36601. }
  36602. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36603. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36604. }
  36605. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36606. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36607. }
  36608. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36609. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36610. }
  36611. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36612. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36613. }
  36614. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36615. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36616. }
  36617. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36618. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36619. }
  36620. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36621. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36622. }
  36623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36624. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36625. }
  36626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36627. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36628. }
  36629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36630. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36631. }
  36632. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36633. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36634. }
  36635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36636. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36637. }
  36638. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36639. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36640. }
  36641. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36642. return result;
  36643. };
  36644. /**
  36645. * Creates the VertexData for a Ribbon
  36646. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36647. * * pathArray array of paths, each of which an array of successive Vector3
  36648. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36649. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36650. * * 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
  36651. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36652. * * 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)
  36653. * * 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)
  36654. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36655. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36656. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36657. * @returns the VertexData of the ribbon
  36658. */
  36659. VertexData.CreateRibbon = function (options) {
  36660. var pathArray = options.pathArray;
  36661. var closeArray = options.closeArray || false;
  36662. var closePath = options.closePath || false;
  36663. var invertUV = options.invertUV || false;
  36664. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36665. var offset = options.offset || defaultOffset;
  36666. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36667. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36668. var customUV = options.uvs;
  36669. var customColors = options.colors;
  36670. var positions = [];
  36671. var indices = [];
  36672. var normals = [];
  36673. var uvs = [];
  36674. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36675. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36676. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36677. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36678. var minlg; // minimal length among all paths from pathArray
  36679. var lg = []; // array of path lengths : nb of vertex per path
  36680. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36681. var p; // path iterator
  36682. var i; // point iterator
  36683. var j; // point iterator
  36684. // if single path in pathArray
  36685. if (pathArray.length < 2) {
  36686. var ar1 = [];
  36687. var ar2 = [];
  36688. for (i = 0; i < pathArray[0].length - offset; i++) {
  36689. ar1.push(pathArray[0][i]);
  36690. ar2.push(pathArray[0][i + offset]);
  36691. }
  36692. pathArray = [ar1, ar2];
  36693. }
  36694. // positions and horizontal distances (u)
  36695. var idc = 0;
  36696. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36697. var path;
  36698. var l;
  36699. minlg = pathArray[0].length;
  36700. var vectlg;
  36701. var dist;
  36702. for (p = 0; p < pathArray.length; p++) {
  36703. uTotalDistance[p] = 0;
  36704. us[p] = [0];
  36705. path = pathArray[p];
  36706. l = path.length;
  36707. minlg = (minlg < l) ? minlg : l;
  36708. j = 0;
  36709. while (j < l) {
  36710. positions.push(path[j].x, path[j].y, path[j].z);
  36711. if (j > 0) {
  36712. vectlg = path[j].subtract(path[j - 1]).length();
  36713. dist = vectlg + uTotalDistance[p];
  36714. us[p].push(dist);
  36715. uTotalDistance[p] = dist;
  36716. }
  36717. j++;
  36718. }
  36719. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36720. j--;
  36721. positions.push(path[0].x, path[0].y, path[0].z);
  36722. vectlg = path[j].subtract(path[0]).length();
  36723. dist = vectlg + uTotalDistance[p];
  36724. us[p].push(dist);
  36725. uTotalDistance[p] = dist;
  36726. }
  36727. lg[p] = l + closePathCorr;
  36728. idx[p] = idc;
  36729. idc += (l + closePathCorr);
  36730. }
  36731. // vertical distances (v)
  36732. var path1;
  36733. var path2;
  36734. var vertex1 = null;
  36735. var vertex2 = null;
  36736. for (i = 0; i < minlg + closePathCorr; i++) {
  36737. vTotalDistance[i] = 0;
  36738. vs[i] = [0];
  36739. for (p = 0; p < pathArray.length - 1; p++) {
  36740. path1 = pathArray[p];
  36741. path2 = pathArray[p + 1];
  36742. if (i === minlg) { // closePath
  36743. vertex1 = path1[0];
  36744. vertex2 = path2[0];
  36745. }
  36746. else {
  36747. vertex1 = path1[i];
  36748. vertex2 = path2[i];
  36749. }
  36750. vectlg = vertex2.subtract(vertex1).length();
  36751. dist = vectlg + vTotalDistance[i];
  36752. vs[i].push(dist);
  36753. vTotalDistance[i] = dist;
  36754. }
  36755. if (closeArray && vertex2 && vertex1) {
  36756. path1 = pathArray[p];
  36757. path2 = pathArray[0];
  36758. if (i === minlg) { // closePath
  36759. vertex2 = path2[0];
  36760. }
  36761. vectlg = vertex2.subtract(vertex1).length();
  36762. dist = vectlg + vTotalDistance[i];
  36763. vTotalDistance[i] = dist;
  36764. }
  36765. }
  36766. // uvs
  36767. var u;
  36768. var v;
  36769. if (customUV) {
  36770. for (p = 0; p < customUV.length; p++) {
  36771. uvs.push(customUV[p].x, customUV[p].y);
  36772. }
  36773. }
  36774. else {
  36775. for (p = 0; p < pathArray.length; p++) {
  36776. for (i = 0; i < minlg + closePathCorr; i++) {
  36777. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36778. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36779. if (invertUV) {
  36780. uvs.push(v, u);
  36781. }
  36782. else {
  36783. uvs.push(u, v);
  36784. }
  36785. }
  36786. }
  36787. }
  36788. // indices
  36789. p = 0; // path index
  36790. var pi = 0; // positions array index
  36791. var l1 = lg[p] - 1; // path1 length
  36792. var l2 = lg[p + 1] - 1; // path2 length
  36793. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36794. var shft = idx[1] - idx[0]; // shift
  36795. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36796. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36797. // 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
  36798. indices.push(pi, pi + shft, pi + 1);
  36799. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36800. pi += 1;
  36801. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36802. p++;
  36803. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36804. shft = idx[0] - idx[p];
  36805. l1 = lg[p] - 1;
  36806. l2 = lg[0] - 1;
  36807. }
  36808. else {
  36809. shft = idx[p + 1] - idx[p];
  36810. l1 = lg[p] - 1;
  36811. l2 = lg[p + 1] - 1;
  36812. }
  36813. pi = idx[p];
  36814. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36815. }
  36816. }
  36817. // normals
  36818. VertexData.ComputeNormals(positions, indices, normals);
  36819. if (closePath) { // update both the first and last vertex normals to their average value
  36820. var indexFirst = 0;
  36821. var indexLast = 0;
  36822. for (p = 0; p < pathArray.length; p++) {
  36823. indexFirst = idx[p] * 3;
  36824. if (p + 1 < pathArray.length) {
  36825. indexLast = (idx[p + 1] - 1) * 3;
  36826. }
  36827. else {
  36828. indexLast = normals.length - 3;
  36829. }
  36830. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36831. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36832. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36833. normals[indexLast] = normals[indexFirst];
  36834. normals[indexLast + 1] = normals[indexFirst + 1];
  36835. normals[indexLast + 2] = normals[indexFirst + 2];
  36836. }
  36837. }
  36838. // sides
  36839. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36840. // Colors
  36841. var colors = null;
  36842. if (customColors) {
  36843. colors = new Float32Array(customColors.length * 4);
  36844. for (var c = 0; c < customColors.length; c++) {
  36845. colors[c * 4] = customColors[c].r;
  36846. colors[c * 4 + 1] = customColors[c].g;
  36847. colors[c * 4 + 2] = customColors[c].b;
  36848. colors[c * 4 + 3] = customColors[c].a;
  36849. }
  36850. }
  36851. // Result
  36852. var vertexData = new VertexData();
  36853. var positions32 = new Float32Array(positions);
  36854. var normals32 = new Float32Array(normals);
  36855. var uvs32 = new Float32Array(uvs);
  36856. vertexData.indices = indices;
  36857. vertexData.positions = positions32;
  36858. vertexData.normals = normals32;
  36859. vertexData.uvs = uvs32;
  36860. if (colors) {
  36861. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36862. }
  36863. if (closePath) {
  36864. vertexData._idx = idx;
  36865. }
  36866. return vertexData;
  36867. };
  36868. /**
  36869. * Creates the VertexData for a box
  36870. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36871. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36872. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36873. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36874. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36875. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36876. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36877. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36878. * * 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)
  36879. * * 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)
  36880. * @returns the VertexData of the box
  36881. */
  36882. VertexData.CreateBox = function (options) {
  36883. var normalsSource = [
  36884. new BABYLON.Vector3(0, 0, 1),
  36885. new BABYLON.Vector3(0, 0, -1),
  36886. new BABYLON.Vector3(1, 0, 0),
  36887. new BABYLON.Vector3(-1, 0, 0),
  36888. new BABYLON.Vector3(0, 1, 0),
  36889. new BABYLON.Vector3(0, -1, 0)
  36890. ];
  36891. var indices = [];
  36892. var positions = [];
  36893. var normals = [];
  36894. var uvs = [];
  36895. var width = options.width || options.size || 1;
  36896. var height = options.height || options.size || 1;
  36897. var depth = options.depth || options.size || 1;
  36898. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36899. var faceUV = options.faceUV || new Array(6);
  36900. var faceColors = options.faceColors;
  36901. var colors = [];
  36902. // default face colors and UV if undefined
  36903. for (var f = 0; f < 6; f++) {
  36904. if (faceUV[f] === undefined) {
  36905. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36906. }
  36907. if (faceColors && faceColors[f] === undefined) {
  36908. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36909. }
  36910. }
  36911. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36912. // Create each face in turn.
  36913. for (var index = 0; index < normalsSource.length; index++) {
  36914. var normal = normalsSource[index];
  36915. // Get two vectors perpendicular to the face normal and to each other.
  36916. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36917. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36918. // Six indices (two triangles) per face.
  36919. var verticesLength = positions.length / 3;
  36920. indices.push(verticesLength);
  36921. indices.push(verticesLength + 1);
  36922. indices.push(verticesLength + 2);
  36923. indices.push(verticesLength);
  36924. indices.push(verticesLength + 2);
  36925. indices.push(verticesLength + 3);
  36926. // Four vertices per face.
  36927. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36928. positions.push(vertex.x, vertex.y, vertex.z);
  36929. normals.push(normal.x, normal.y, normal.z);
  36930. uvs.push(faceUV[index].z, faceUV[index].w);
  36931. if (faceColors) {
  36932. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36933. }
  36934. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36935. positions.push(vertex.x, vertex.y, vertex.z);
  36936. normals.push(normal.x, normal.y, normal.z);
  36937. uvs.push(faceUV[index].x, faceUV[index].w);
  36938. if (faceColors) {
  36939. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36940. }
  36941. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36942. positions.push(vertex.x, vertex.y, vertex.z);
  36943. normals.push(normal.x, normal.y, normal.z);
  36944. uvs.push(faceUV[index].x, faceUV[index].y);
  36945. if (faceColors) {
  36946. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36947. }
  36948. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36949. positions.push(vertex.x, vertex.y, vertex.z);
  36950. normals.push(normal.x, normal.y, normal.z);
  36951. uvs.push(faceUV[index].z, faceUV[index].y);
  36952. if (faceColors) {
  36953. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36954. }
  36955. }
  36956. // sides
  36957. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36958. // Result
  36959. var vertexData = new VertexData();
  36960. vertexData.indices = indices;
  36961. vertexData.positions = positions;
  36962. vertexData.normals = normals;
  36963. vertexData.uvs = uvs;
  36964. if (faceColors) {
  36965. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36966. vertexData.colors = totalColors;
  36967. }
  36968. return vertexData;
  36969. };
  36970. /**
  36971. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36972. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36973. * * segments sets the number of horizontal strips optional, default 32
  36974. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36975. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36976. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36977. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36978. * * 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
  36979. * * 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
  36980. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36981. * * 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)
  36982. * * 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)
  36983. * @returns the VertexData of the ellipsoid
  36984. */
  36985. VertexData.CreateSphere = function (options) {
  36986. var segments = options.segments || 32;
  36987. var diameterX = options.diameterX || options.diameter || 1;
  36988. var diameterY = options.diameterY || options.diameter || 1;
  36989. var diameterZ = options.diameterZ || options.diameter || 1;
  36990. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36991. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36992. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36993. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36994. var totalZRotationSteps = 2 + segments;
  36995. var totalYRotationSteps = 2 * totalZRotationSteps;
  36996. var indices = [];
  36997. var positions = [];
  36998. var normals = [];
  36999. var uvs = [];
  37000. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37001. var normalizedZ = zRotationStep / totalZRotationSteps;
  37002. var angleZ = normalizedZ * Math.PI * slice;
  37003. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37004. var normalizedY = yRotationStep / totalYRotationSteps;
  37005. var angleY = normalizedY * Math.PI * 2 * arc;
  37006. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37007. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37008. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37009. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37010. var vertex = complete.multiply(radius);
  37011. var normal = complete.divide(radius).normalize();
  37012. positions.push(vertex.x, vertex.y, vertex.z);
  37013. normals.push(normal.x, normal.y, normal.z);
  37014. uvs.push(normalizedY, normalizedZ);
  37015. }
  37016. if (zRotationStep > 0) {
  37017. var verticesCount = positions.length / 3;
  37018. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37019. indices.push((firstIndex));
  37020. indices.push((firstIndex + 1));
  37021. indices.push(firstIndex + totalYRotationSteps + 1);
  37022. indices.push((firstIndex + totalYRotationSteps + 1));
  37023. indices.push((firstIndex + 1));
  37024. indices.push((firstIndex + totalYRotationSteps + 2));
  37025. }
  37026. }
  37027. }
  37028. // Sides
  37029. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37030. // Result
  37031. var vertexData = new VertexData();
  37032. vertexData.indices = indices;
  37033. vertexData.positions = positions;
  37034. vertexData.normals = normals;
  37035. vertexData.uvs = uvs;
  37036. return vertexData;
  37037. };
  37038. /**
  37039. * Creates the VertexData for a cylinder, cone or prism
  37040. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37041. * * height sets the height (y direction) of the cylinder, optional, default 2
  37042. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37043. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37044. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37045. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37046. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37047. * * 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
  37048. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37049. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37050. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37051. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37052. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37053. * * 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)
  37054. * * 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)
  37055. * @returns the VertexData of the cylinder, cone or prism
  37056. */
  37057. VertexData.CreateCylinder = function (options) {
  37058. var height = options.height || 2;
  37059. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37060. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37061. var tessellation = options.tessellation || 24;
  37062. var subdivisions = options.subdivisions || 1;
  37063. var hasRings = options.hasRings ? true : false;
  37064. var enclose = options.enclose ? true : false;
  37065. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37066. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37067. var faceUV = options.faceUV || new Array(3);
  37068. var faceColors = options.faceColors;
  37069. // default face colors and UV if undefined
  37070. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37071. var ringNb = (hasRings) ? subdivisions : 1;
  37072. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37073. var f;
  37074. for (f = 0; f < surfaceNb; f++) {
  37075. if (faceColors && faceColors[f] === undefined) {
  37076. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37077. }
  37078. }
  37079. for (f = 0; f < surfaceNb; f++) {
  37080. if (faceUV && faceUV[f] === undefined) {
  37081. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37082. }
  37083. }
  37084. var indices = new Array();
  37085. var positions = new Array();
  37086. var normals = new Array();
  37087. var uvs = new Array();
  37088. var colors = new Array();
  37089. var angle_step = Math.PI * 2 * arc / tessellation;
  37090. var angle;
  37091. var h;
  37092. var radius;
  37093. var tan = (diameterBottom - diameterTop) / 2 / height;
  37094. var ringVertex = BABYLON.Vector3.Zero();
  37095. var ringNormal = BABYLON.Vector3.Zero();
  37096. var ringFirstVertex = BABYLON.Vector3.Zero();
  37097. var ringFirstNormal = BABYLON.Vector3.Zero();
  37098. var quadNormal = BABYLON.Vector3.Zero();
  37099. var Y = BABYLON.Axis.Y;
  37100. // positions, normals, uvs
  37101. var i;
  37102. var j;
  37103. var r;
  37104. var ringIdx = 1;
  37105. var s = 1; // surface index
  37106. var cs = 0;
  37107. var v = 0;
  37108. for (i = 0; i <= subdivisions; i++) {
  37109. h = i / subdivisions;
  37110. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37111. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37112. for (r = 0; r < ringIdx; r++) {
  37113. if (hasRings) {
  37114. s += r;
  37115. }
  37116. if (enclose) {
  37117. s += 2 * r;
  37118. }
  37119. for (j = 0; j <= tessellation; j++) {
  37120. angle = j * angle_step;
  37121. // position
  37122. ringVertex.x = Math.cos(-angle) * radius;
  37123. ringVertex.y = -height / 2 + h * height;
  37124. ringVertex.z = Math.sin(-angle) * radius;
  37125. // normal
  37126. if (diameterTop === 0 && i === subdivisions) {
  37127. // if no top cap, reuse former normals
  37128. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37129. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37130. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37131. }
  37132. else {
  37133. ringNormal.x = ringVertex.x;
  37134. ringNormal.z = ringVertex.z;
  37135. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37136. ringNormal.normalize();
  37137. }
  37138. // keep first ring vertex values for enclose
  37139. if (j === 0) {
  37140. ringFirstVertex.copyFrom(ringVertex);
  37141. ringFirstNormal.copyFrom(ringNormal);
  37142. }
  37143. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37144. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37145. if (hasRings) {
  37146. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37147. }
  37148. else {
  37149. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37150. }
  37151. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37152. if (faceColors) {
  37153. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37154. }
  37155. }
  37156. // if enclose, add four vertices and their dedicated normals
  37157. if (arc !== 1 && enclose) {
  37158. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37159. positions.push(0, ringVertex.y, 0);
  37160. positions.push(0, ringVertex.y, 0);
  37161. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37162. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37163. quadNormal.normalize();
  37164. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37165. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37166. quadNormal.normalize();
  37167. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37168. if (hasRings) {
  37169. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37170. }
  37171. else {
  37172. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37173. }
  37174. uvs.push(faceUV[s + 1].x, v);
  37175. uvs.push(faceUV[s + 1].z, v);
  37176. if (hasRings) {
  37177. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37178. }
  37179. else {
  37180. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37181. }
  37182. uvs.push(faceUV[s + 2].x, v);
  37183. uvs.push(faceUV[s + 2].z, v);
  37184. if (faceColors) {
  37185. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37186. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37187. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37188. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37189. }
  37190. }
  37191. if (cs !== s) {
  37192. cs = s;
  37193. }
  37194. }
  37195. }
  37196. // indices
  37197. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37198. var s;
  37199. i = 0;
  37200. for (s = 0; s < subdivisions; s++) {
  37201. var i0 = 0;
  37202. var i1 = 0;
  37203. var i2 = 0;
  37204. var i3 = 0;
  37205. for (j = 0; j < tessellation; j++) {
  37206. i0 = i * (e + 1) + j;
  37207. i1 = (i + 1) * (e + 1) + j;
  37208. i2 = i * (e + 1) + (j + 1);
  37209. i3 = (i + 1) * (e + 1) + (j + 1);
  37210. indices.push(i0, i1, i2);
  37211. indices.push(i3, i2, i1);
  37212. }
  37213. if (arc !== 1 && enclose) { // if enclose, add two quads
  37214. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37215. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37216. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37217. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37218. }
  37219. i = (hasRings) ? (i + 2) : (i + 1);
  37220. }
  37221. // Caps
  37222. var createCylinderCap = function (isTop) {
  37223. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37224. if (radius === 0) {
  37225. return;
  37226. }
  37227. // Cap positions, normals & uvs
  37228. var angle;
  37229. var circleVector;
  37230. var i;
  37231. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37232. var c = null;
  37233. if (faceColors) {
  37234. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37235. }
  37236. // cap center
  37237. var vbase = positions.length / 3;
  37238. var offset = isTop ? height / 2 : -height / 2;
  37239. var center = new BABYLON.Vector3(0, offset, 0);
  37240. positions.push(center.x, center.y, center.z);
  37241. normals.push(0, isTop ? 1 : -1, 0);
  37242. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37243. if (c) {
  37244. colors.push(c.r, c.g, c.b, c.a);
  37245. }
  37246. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37247. for (i = 0; i <= tessellation; i++) {
  37248. angle = Math.PI * 2 * i * arc / tessellation;
  37249. var cos = Math.cos(-angle);
  37250. var sin = Math.sin(-angle);
  37251. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37252. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37253. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37254. normals.push(0, isTop ? 1 : -1, 0);
  37255. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37256. if (c) {
  37257. colors.push(c.r, c.g, c.b, c.a);
  37258. }
  37259. }
  37260. // Cap indices
  37261. for (i = 0; i < tessellation; i++) {
  37262. if (!isTop) {
  37263. indices.push(vbase);
  37264. indices.push(vbase + (i + 1));
  37265. indices.push(vbase + (i + 2));
  37266. }
  37267. else {
  37268. indices.push(vbase);
  37269. indices.push(vbase + (i + 2));
  37270. indices.push(vbase + (i + 1));
  37271. }
  37272. }
  37273. };
  37274. // add caps to geometry
  37275. createCylinderCap(false);
  37276. createCylinderCap(true);
  37277. // Sides
  37278. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37279. var vertexData = new VertexData();
  37280. vertexData.indices = indices;
  37281. vertexData.positions = positions;
  37282. vertexData.normals = normals;
  37283. vertexData.uvs = uvs;
  37284. if (faceColors) {
  37285. vertexData.colors = colors;
  37286. }
  37287. return vertexData;
  37288. };
  37289. /**
  37290. * Creates the VertexData for a torus
  37291. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37292. * * diameter the diameter of the torus, optional default 1
  37293. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37294. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37295. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37296. * * 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)
  37297. * * 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)
  37298. * @returns the VertexData of the torus
  37299. */
  37300. VertexData.CreateTorus = function (options) {
  37301. var indices = [];
  37302. var positions = [];
  37303. var normals = [];
  37304. var uvs = [];
  37305. var diameter = options.diameter || 1;
  37306. var thickness = options.thickness || 0.5;
  37307. var tessellation = options.tessellation || 16;
  37308. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37309. var stride = tessellation + 1;
  37310. for (var i = 0; i <= tessellation; i++) {
  37311. var u = i / tessellation;
  37312. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37313. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37314. for (var j = 0; j <= tessellation; j++) {
  37315. var v = 1 - j / tessellation;
  37316. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37317. var dx = Math.cos(innerAngle);
  37318. var dy = Math.sin(innerAngle);
  37319. // Create a vertex.
  37320. var normal = new BABYLON.Vector3(dx, dy, 0);
  37321. var position = normal.scale(thickness / 2);
  37322. var textureCoordinate = new BABYLON.Vector2(u, v);
  37323. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37324. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37325. positions.push(position.x, position.y, position.z);
  37326. normals.push(normal.x, normal.y, normal.z);
  37327. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37328. // And create indices for two triangles.
  37329. var nextI = (i + 1) % stride;
  37330. var nextJ = (j + 1) % stride;
  37331. indices.push(i * stride + j);
  37332. indices.push(i * stride + nextJ);
  37333. indices.push(nextI * stride + j);
  37334. indices.push(i * stride + nextJ);
  37335. indices.push(nextI * stride + nextJ);
  37336. indices.push(nextI * stride + j);
  37337. }
  37338. }
  37339. // Sides
  37340. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37341. // Result
  37342. var vertexData = new VertexData();
  37343. vertexData.indices = indices;
  37344. vertexData.positions = positions;
  37345. vertexData.normals = normals;
  37346. vertexData.uvs = uvs;
  37347. return vertexData;
  37348. };
  37349. /**
  37350. * Creates the VertexData of the LineSystem
  37351. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37352. * - lines an array of lines, each line being an array of successive Vector3
  37353. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37354. * @returns the VertexData of the LineSystem
  37355. */
  37356. VertexData.CreateLineSystem = function (options) {
  37357. var indices = [];
  37358. var positions = [];
  37359. var lines = options.lines;
  37360. var colors = options.colors;
  37361. var vertexColors = [];
  37362. var idx = 0;
  37363. for (var l = 0; l < lines.length; l++) {
  37364. var points = lines[l];
  37365. for (var index = 0; index < points.length; index++) {
  37366. positions.push(points[index].x, points[index].y, points[index].z);
  37367. if (colors) {
  37368. var color = colors[l];
  37369. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37370. }
  37371. if (index > 0) {
  37372. indices.push(idx - 1);
  37373. indices.push(idx);
  37374. }
  37375. idx++;
  37376. }
  37377. }
  37378. var vertexData = new VertexData();
  37379. vertexData.indices = indices;
  37380. vertexData.positions = positions;
  37381. if (colors) {
  37382. vertexData.colors = vertexColors;
  37383. }
  37384. return vertexData;
  37385. };
  37386. /**
  37387. * Create the VertexData for a DashedLines
  37388. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37389. * - points an array successive Vector3
  37390. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37391. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37392. * - dashNb the intended total number of dashes, optional, default 200
  37393. * @returns the VertexData for the DashedLines
  37394. */
  37395. VertexData.CreateDashedLines = function (options) {
  37396. var dashSize = options.dashSize || 3;
  37397. var gapSize = options.gapSize || 1;
  37398. var dashNb = options.dashNb || 200;
  37399. var points = options.points;
  37400. var positions = new Array();
  37401. var indices = new Array();
  37402. var curvect = BABYLON.Vector3.Zero();
  37403. var lg = 0;
  37404. var nb = 0;
  37405. var shft = 0;
  37406. var dashshft = 0;
  37407. var curshft = 0;
  37408. var idx = 0;
  37409. var i = 0;
  37410. for (i = 0; i < points.length - 1; i++) {
  37411. points[i + 1].subtractToRef(points[i], curvect);
  37412. lg += curvect.length();
  37413. }
  37414. shft = lg / dashNb;
  37415. dashshft = dashSize * shft / (dashSize + gapSize);
  37416. for (i = 0; i < points.length - 1; i++) {
  37417. points[i + 1].subtractToRef(points[i], curvect);
  37418. nb = Math.floor(curvect.length() / shft);
  37419. curvect.normalize();
  37420. for (var j = 0; j < nb; j++) {
  37421. curshft = shft * j;
  37422. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37423. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37424. indices.push(idx, idx + 1);
  37425. idx += 2;
  37426. }
  37427. }
  37428. // Result
  37429. var vertexData = new VertexData();
  37430. vertexData.positions = positions;
  37431. vertexData.indices = indices;
  37432. return vertexData;
  37433. };
  37434. /**
  37435. * Creates the VertexData for a Ground
  37436. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37437. * - width the width (x direction) of the ground, optional, default 1
  37438. * - height the height (z direction) of the ground, optional, default 1
  37439. * - subdivisions the number of subdivisions per side, optional, default 1
  37440. * @returns the VertexData of the Ground
  37441. */
  37442. VertexData.CreateGround = function (options) {
  37443. var indices = [];
  37444. var positions = [];
  37445. var normals = [];
  37446. var uvs = [];
  37447. var row, col;
  37448. var width = options.width || 1;
  37449. var height = options.height || 1;
  37450. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37451. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37452. for (row = 0; row <= subdivisionsY; row++) {
  37453. for (col = 0; col <= subdivisionsX; col++) {
  37454. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37455. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37456. positions.push(position.x, position.y, position.z);
  37457. normals.push(normal.x, normal.y, normal.z);
  37458. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37459. }
  37460. }
  37461. for (row = 0; row < subdivisionsY; row++) {
  37462. for (col = 0; col < subdivisionsX; col++) {
  37463. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37464. indices.push(col + 1 + row * (subdivisionsX + 1));
  37465. indices.push(col + row * (subdivisionsX + 1));
  37466. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37467. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37468. indices.push(col + row * (subdivisionsX + 1));
  37469. }
  37470. }
  37471. // Result
  37472. var vertexData = new VertexData();
  37473. vertexData.indices = indices;
  37474. vertexData.positions = positions;
  37475. vertexData.normals = normals;
  37476. vertexData.uvs = uvs;
  37477. return vertexData;
  37478. };
  37479. /**
  37480. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37481. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37482. * * xmin the ground minimum X coordinate, optional, default -1
  37483. * * zmin the ground minimum Z coordinate, optional, default -1
  37484. * * xmax the ground maximum X coordinate, optional, default 1
  37485. * * zmax the ground maximum Z coordinate, optional, default 1
  37486. * * 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}
  37487. * * 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}
  37488. * @returns the VertexData of the TiledGround
  37489. */
  37490. VertexData.CreateTiledGround = function (options) {
  37491. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37492. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37493. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37494. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37495. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37496. var precision = options.precision || { w: 1, h: 1 };
  37497. var indices = new Array();
  37498. var positions = new Array();
  37499. var normals = new Array();
  37500. var uvs = new Array();
  37501. var row, col, tileRow, tileCol;
  37502. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37503. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37504. precision.w = (precision.w < 1) ? 1 : precision.w;
  37505. precision.h = (precision.h < 1) ? 1 : precision.h;
  37506. var tileSize = {
  37507. 'w': (xmax - xmin) / subdivisions.w,
  37508. 'h': (zmax - zmin) / subdivisions.h
  37509. };
  37510. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37511. // Indices
  37512. var base = positions.length / 3;
  37513. var rowLength = precision.w + 1;
  37514. for (row = 0; row < precision.h; row++) {
  37515. for (col = 0; col < precision.w; col++) {
  37516. var square = [
  37517. base + col + row * rowLength,
  37518. base + (col + 1) + row * rowLength,
  37519. base + (col + 1) + (row + 1) * rowLength,
  37520. base + col + (row + 1) * rowLength
  37521. ];
  37522. indices.push(square[1]);
  37523. indices.push(square[2]);
  37524. indices.push(square[3]);
  37525. indices.push(square[0]);
  37526. indices.push(square[1]);
  37527. indices.push(square[3]);
  37528. }
  37529. }
  37530. // Position, normals and uvs
  37531. var position = BABYLON.Vector3.Zero();
  37532. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37533. for (row = 0; row <= precision.h; row++) {
  37534. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37535. for (col = 0; col <= precision.w; col++) {
  37536. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37537. position.y = 0;
  37538. positions.push(position.x, position.y, position.z);
  37539. normals.push(normal.x, normal.y, normal.z);
  37540. uvs.push(col / precision.w, row / precision.h);
  37541. }
  37542. }
  37543. }
  37544. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37545. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37546. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37547. }
  37548. }
  37549. // Result
  37550. var vertexData = new VertexData();
  37551. vertexData.indices = indices;
  37552. vertexData.positions = positions;
  37553. vertexData.normals = normals;
  37554. vertexData.uvs = uvs;
  37555. return vertexData;
  37556. };
  37557. /**
  37558. * Creates the VertexData of the Ground designed from a heightmap
  37559. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37560. * * width the width (x direction) of the ground
  37561. * * height the height (z direction) of the ground
  37562. * * subdivisions the number of subdivisions per side
  37563. * * minHeight the minimum altitude on the ground, optional, default 0
  37564. * * maxHeight the maximum altitude on the ground, optional default 1
  37565. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37566. * * buffer the array holding the image color data
  37567. * * bufferWidth the width of image
  37568. * * bufferHeight the height of image
  37569. * @returns the VertexData of the Ground designed from a heightmap
  37570. */
  37571. VertexData.CreateGroundFromHeightMap = function (options) {
  37572. var indices = [];
  37573. var positions = [];
  37574. var normals = [];
  37575. var uvs = [];
  37576. var row, col;
  37577. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37578. // Vertices
  37579. for (row = 0; row <= options.subdivisions; row++) {
  37580. for (col = 0; col <= options.subdivisions; col++) {
  37581. 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));
  37582. // Compute height
  37583. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37584. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37585. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37586. var r = options.buffer[pos] / 255.0;
  37587. var g = options.buffer[pos + 1] / 255.0;
  37588. var b = options.buffer[pos + 2] / 255.0;
  37589. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37590. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37591. // Add vertex
  37592. positions.push(position.x, position.y, position.z);
  37593. normals.push(0, 0, 0);
  37594. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37595. }
  37596. }
  37597. // Indices
  37598. for (row = 0; row < options.subdivisions; row++) {
  37599. for (col = 0; col < options.subdivisions; col++) {
  37600. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37601. indices.push(col + 1 + row * (options.subdivisions + 1));
  37602. indices.push(col + row * (options.subdivisions + 1));
  37603. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37604. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37605. indices.push(col + row * (options.subdivisions + 1));
  37606. }
  37607. }
  37608. // Normals
  37609. VertexData.ComputeNormals(positions, indices, normals);
  37610. // Result
  37611. var vertexData = new VertexData();
  37612. vertexData.indices = indices;
  37613. vertexData.positions = positions;
  37614. vertexData.normals = normals;
  37615. vertexData.uvs = uvs;
  37616. return vertexData;
  37617. };
  37618. /**
  37619. * Creates the VertexData for a Plane
  37620. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37621. * * size sets the width and height of the plane to the value of size, optional default 1
  37622. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37623. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37624. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37625. * * 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)
  37626. * * 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)
  37627. * @returns the VertexData of the box
  37628. */
  37629. VertexData.CreatePlane = function (options) {
  37630. var indices = [];
  37631. var positions = [];
  37632. var normals = [];
  37633. var uvs = [];
  37634. var width = options.width || options.size || 1;
  37635. var height = options.height || options.size || 1;
  37636. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37637. // Vertices
  37638. var halfWidth = width / 2.0;
  37639. var halfHeight = height / 2.0;
  37640. positions.push(-halfWidth, -halfHeight, 0);
  37641. normals.push(0, 0, -1.0);
  37642. uvs.push(0.0, 0.0);
  37643. positions.push(halfWidth, -halfHeight, 0);
  37644. normals.push(0, 0, -1.0);
  37645. uvs.push(1.0, 0.0);
  37646. positions.push(halfWidth, halfHeight, 0);
  37647. normals.push(0, 0, -1.0);
  37648. uvs.push(1.0, 1.0);
  37649. positions.push(-halfWidth, halfHeight, 0);
  37650. normals.push(0, 0, -1.0);
  37651. uvs.push(0.0, 1.0);
  37652. // Indices
  37653. indices.push(0);
  37654. indices.push(1);
  37655. indices.push(2);
  37656. indices.push(0);
  37657. indices.push(2);
  37658. indices.push(3);
  37659. // Sides
  37660. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37661. // Result
  37662. var vertexData = new VertexData();
  37663. vertexData.indices = indices;
  37664. vertexData.positions = positions;
  37665. vertexData.normals = normals;
  37666. vertexData.uvs = uvs;
  37667. return vertexData;
  37668. };
  37669. /**
  37670. * Creates the VertexData of the Disc or regular Polygon
  37671. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37672. * * radius the radius of the disc, optional default 0.5
  37673. * * tessellation the number of polygon sides, optional, default 64
  37674. * * 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
  37675. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37676. * * 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)
  37677. * * 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)
  37678. * @returns the VertexData of the box
  37679. */
  37680. VertexData.CreateDisc = function (options) {
  37681. var positions = new Array();
  37682. var indices = new Array();
  37683. var normals = new Array();
  37684. var uvs = new Array();
  37685. var radius = options.radius || 0.5;
  37686. var tessellation = options.tessellation || 64;
  37687. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37688. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37689. // positions and uvs
  37690. positions.push(0, 0, 0); // disc center first
  37691. uvs.push(0.5, 0.5);
  37692. var theta = Math.PI * 2 * arc;
  37693. var step = theta / tessellation;
  37694. for (var a = 0; a < theta; a += step) {
  37695. var x = Math.cos(a);
  37696. var y = Math.sin(a);
  37697. var u = (x + 1) / 2;
  37698. var v = (1 - y) / 2;
  37699. positions.push(radius * x, radius * y, 0);
  37700. uvs.push(u, v);
  37701. }
  37702. if (arc === 1) {
  37703. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37704. uvs.push(uvs[2], uvs[3]);
  37705. }
  37706. //indices
  37707. var vertexNb = positions.length / 3;
  37708. for (var i = 1; i < vertexNb - 1; i++) {
  37709. indices.push(i + 1, 0, i);
  37710. }
  37711. // result
  37712. VertexData.ComputeNormals(positions, indices, normals);
  37713. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37714. var vertexData = new VertexData();
  37715. vertexData.indices = indices;
  37716. vertexData.positions = positions;
  37717. vertexData.normals = normals;
  37718. vertexData.uvs = uvs;
  37719. return vertexData;
  37720. };
  37721. /**
  37722. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37723. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37724. * @param polygon a mesh built from polygonTriangulation.build()
  37725. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37726. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37727. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37728. * @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)
  37729. * @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)
  37730. * @returns the VertexData of the Polygon
  37731. */
  37732. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37733. var faceUV = fUV || new Array(3);
  37734. var faceColors = fColors;
  37735. var colors = [];
  37736. // default face colors and UV if undefined
  37737. for (var f = 0; f < 3; f++) {
  37738. if (faceUV[f] === undefined) {
  37739. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37740. }
  37741. if (faceColors && faceColors[f] === undefined) {
  37742. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37743. }
  37744. }
  37745. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37746. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37747. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37748. var indices = polygon.getIndices();
  37749. // set face colours and textures
  37750. var idx = 0;
  37751. var face = 0;
  37752. for (var index = 0; index < normals.length; index += 3) {
  37753. //Edge Face no. 1
  37754. if (Math.abs(normals[index + 1]) < 0.001) {
  37755. face = 1;
  37756. }
  37757. //Top Face no. 0
  37758. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37759. face = 0;
  37760. }
  37761. //Bottom Face no. 2
  37762. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37763. face = 2;
  37764. }
  37765. idx = index / 3;
  37766. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37767. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37768. if (faceColors) {
  37769. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37770. }
  37771. }
  37772. // sides
  37773. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37774. // Result
  37775. var vertexData = new VertexData();
  37776. vertexData.indices = indices;
  37777. vertexData.positions = positions;
  37778. vertexData.normals = normals;
  37779. vertexData.uvs = uvs;
  37780. if (faceColors) {
  37781. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37782. vertexData.colors = totalColors;
  37783. }
  37784. return vertexData;
  37785. };
  37786. /**
  37787. * Creates the VertexData of the IcoSphere
  37788. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37789. * * radius the radius of the IcoSphere, optional default 1
  37790. * * radiusX allows stretching in the x direction, optional, default radius
  37791. * * radiusY allows stretching in the y direction, optional, default radius
  37792. * * radiusZ allows stretching in the z direction, optional, default radius
  37793. * * flat when true creates a flat shaded mesh, optional, default true
  37794. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37795. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37796. * * 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)
  37797. * * 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)
  37798. * @returns the VertexData of the IcoSphere
  37799. */
  37800. VertexData.CreateIcoSphere = function (options) {
  37801. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37802. var radius = options.radius || 1;
  37803. var flat = (options.flat === undefined) ? true : options.flat;
  37804. var subdivisions = options.subdivisions || 4;
  37805. var radiusX = options.radiusX || radius;
  37806. var radiusY = options.radiusY || radius;
  37807. var radiusZ = options.radiusZ || radius;
  37808. var t = (1 + Math.sqrt(5)) / 2;
  37809. // 12 vertex x,y,z
  37810. var ico_vertices = [
  37811. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37812. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37813. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37814. ];
  37815. // index of 3 vertex makes a face of icopshere
  37816. var ico_indices = [
  37817. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37818. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37819. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37820. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37821. ];
  37822. // vertex for uv have aliased position, not for UV
  37823. var vertices_unalias_id = [
  37824. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37825. // vertex alias
  37826. 0,
  37827. 2,
  37828. 3,
  37829. 3,
  37830. 3,
  37831. 4,
  37832. 7,
  37833. 8,
  37834. 9,
  37835. 9,
  37836. 10,
  37837. 11 // 23: B + 12
  37838. ];
  37839. // uv as integer step (not pixels !)
  37840. var ico_vertexuv = [
  37841. 5, 1, 3, 1, 6, 4, 0, 0,
  37842. 5, 3, 4, 2, 2, 2, 4, 0,
  37843. 2, 0, 1, 1, 6, 0, 6, 2,
  37844. // vertex alias (for same vertex on different faces)
  37845. 0, 4,
  37846. 3, 3,
  37847. 4, 4,
  37848. 3, 1,
  37849. 4, 2,
  37850. 4, 4,
  37851. 0, 2,
  37852. 1, 1,
  37853. 2, 2,
  37854. 3, 3,
  37855. 1, 3,
  37856. 2, 4 // 23: B + 12
  37857. ];
  37858. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37859. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37860. // First island of uv mapping
  37861. // v = 4h 3+ 2
  37862. // v = 3h 9+ 4
  37863. // v = 2h 9+ 5 B
  37864. // v = 1h 9 1 0
  37865. // v = 0h 3 8 7 A
  37866. // u = 0 1 2 3 4 5 6 *a
  37867. // Second island of uv mapping
  37868. // v = 4h 0+ B+ 4+
  37869. // v = 3h A+ 2+
  37870. // v = 2h 7+ 6 3+
  37871. // v = 1h 8+ 3+
  37872. // v = 0h
  37873. // u = 0 1 2 3 4 5 6 *a
  37874. // Face layout on texture UV mapping
  37875. // ============
  37876. // \ 4 /\ 16 / ======
  37877. // \ / \ / /\ 11 /
  37878. // \/ 7 \/ / \ /
  37879. // ======= / 10 \/
  37880. // /\ 17 /\ =======
  37881. // / \ / \ \ 15 /\
  37882. // / 8 \/ 12 \ \ / \
  37883. // ============ \/ 6 \
  37884. // \ 18 /\ ============
  37885. // \ / \ \ 5 /\ 0 /
  37886. // \/ 13 \ \ / \ /
  37887. // ======= \/ 1 \/
  37888. // =============
  37889. // /\ 19 /\ 2 /\
  37890. // / \ / \ / \
  37891. // / 14 \/ 9 \/ 3 \
  37892. // ===================
  37893. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37894. var ustep = 138 / 1024;
  37895. var vstep = 239 / 1024;
  37896. var uoffset = 60 / 1024;
  37897. var voffset = 26 / 1024;
  37898. // Second island should have margin, not to touch the first island
  37899. // avoid any borderline artefact in pixel rounding
  37900. var island_u_offset = -40 / 1024;
  37901. var island_v_offset = +20 / 1024;
  37902. // face is either island 0 or 1 :
  37903. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37904. var island = [
  37905. 0, 0, 0, 0, 1,
  37906. 0, 0, 1, 1, 0,
  37907. 0, 0, 1, 1, 0,
  37908. 0, 1, 1, 1, 0 // 15 - 19
  37909. ];
  37910. var indices = new Array();
  37911. var positions = new Array();
  37912. var normals = new Array();
  37913. var uvs = new Array();
  37914. var current_indice = 0;
  37915. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37916. var face_vertex_pos = new Array(3);
  37917. var face_vertex_uv = new Array(3);
  37918. var v012;
  37919. for (v012 = 0; v012 < 3; v012++) {
  37920. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37921. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37922. }
  37923. // create all with normals
  37924. for (var face = 0; face < 20; face++) {
  37925. // 3 vertex per face
  37926. for (v012 = 0; v012 < 3; v012++) {
  37927. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37928. var v_id = ico_indices[3 * face + v012];
  37929. // vertex have 3D position (x,y,z)
  37930. 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]);
  37931. // Normalize to get normal, then scale to radius
  37932. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37933. // uv Coordinates from vertex ID
  37934. 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);
  37935. }
  37936. // Subdivide the face (interpolate pos, norm, uv)
  37937. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37938. // - norm is linear interpolation of vertex corner normal
  37939. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37940. // - uv is linear interpolation
  37941. //
  37942. // Topology is as below for sub-divide by 2
  37943. // vertex shown as v0,v1,v2
  37944. // interp index is i1 to progress in range [v0,v1[
  37945. // interp index is i2 to progress in range [v0,v2[
  37946. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37947. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37948. //
  37949. //
  37950. // i2 v2
  37951. // ^ ^
  37952. // / / \
  37953. // / / \
  37954. // / / \
  37955. // / / (0,1) \
  37956. // / #---------\
  37957. // / / \ (0,0)'/ \
  37958. // / / \ / \
  37959. // / / \ / \
  37960. // / / (0,0) \ / (1,0) \
  37961. // / #---------#---------\
  37962. // v0 v1
  37963. //
  37964. // --------------------> i1
  37965. //
  37966. // interp of (i1,i2):
  37967. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37968. // along i1 : lerp(x0,x1, i1/(S-i2))
  37969. //
  37970. // centroid of triangle is needed to get help normal computation
  37971. // (c1,c2) are used for centroid location
  37972. var interp_vertex = function (i1, i2, c1, c2) {
  37973. // vertex is interpolated from
  37974. // - face_vertex_pos[0..2]
  37975. // - face_vertex_uv[0..2]
  37976. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37977. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37978. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37979. pos_interp.normalize();
  37980. var vertex_normal;
  37981. if (flat) {
  37982. // in flat mode, recalculate normal as face centroid normal
  37983. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37984. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37985. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37986. }
  37987. else {
  37988. // in smooth mode, recalculate normal from each single vertex position
  37989. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37990. }
  37991. // Vertex normal need correction due to X,Y,Z radius scaling
  37992. vertex_normal.x /= radiusX;
  37993. vertex_normal.y /= radiusY;
  37994. vertex_normal.z /= radiusZ;
  37995. vertex_normal.normalize();
  37996. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37997. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37998. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37999. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38000. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38001. uvs.push(uv_interp.x, uv_interp.y);
  38002. // push each vertex has member of a face
  38003. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38004. indices.push(current_indice);
  38005. current_indice++;
  38006. };
  38007. for (var i2 = 0; i2 < subdivisions; i2++) {
  38008. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38009. // face : (i1,i2) for /\ :
  38010. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38011. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38012. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38013. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38014. if (i1 + i2 + 1 < subdivisions) {
  38015. // face : (i1,i2)' for \/ :
  38016. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38017. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38018. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38019. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38020. }
  38021. }
  38022. }
  38023. }
  38024. // Sides
  38025. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38026. // Result
  38027. var vertexData = new VertexData();
  38028. vertexData.indices = indices;
  38029. vertexData.positions = positions;
  38030. vertexData.normals = normals;
  38031. vertexData.uvs = uvs;
  38032. return vertexData;
  38033. };
  38034. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38035. /**
  38036. * Creates the VertexData for a Polyhedron
  38037. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38038. * * type provided types are:
  38039. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38040. * * 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)
  38041. * * size the size of the IcoSphere, optional default 1
  38042. * * sizeX allows stretching in the x direction, optional, default size
  38043. * * sizeY allows stretching in the y direction, optional, default size
  38044. * * sizeZ allows stretching in the z direction, optional, default size
  38045. * * 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
  38046. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38047. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38048. * * flat when true creates a flat shaded mesh, optional, default true
  38049. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38050. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38051. * * 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)
  38052. * * 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)
  38053. * @returns the VertexData of the Polyhedron
  38054. */
  38055. VertexData.CreatePolyhedron = function (options) {
  38056. // provided polyhedron types :
  38057. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38058. // 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)
  38059. var polyhedra = [];
  38060. 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]] };
  38061. 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]] };
  38062. polyhedra[2] = {
  38063. 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]],
  38064. 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]]
  38065. };
  38066. polyhedra[3] = {
  38067. 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]],
  38068. 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]]
  38069. };
  38070. polyhedra[4] = {
  38071. 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]],
  38072. 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]]
  38073. };
  38074. 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]] };
  38075. 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]] };
  38076. 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]] };
  38077. 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]] };
  38078. 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]] };
  38079. 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]] };
  38080. 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]] };
  38081. 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]] };
  38082. 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]] };
  38083. polyhedra[14] = {
  38084. 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]],
  38085. 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]]
  38086. };
  38087. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38088. var size = options.size;
  38089. var sizeX = options.sizeX || size || 1;
  38090. var sizeY = options.sizeY || size || 1;
  38091. var sizeZ = options.sizeZ || size || 1;
  38092. var data = options.custom || polyhedra[type];
  38093. var nbfaces = data.face.length;
  38094. var faceUV = options.faceUV || new Array(nbfaces);
  38095. var faceColors = options.faceColors;
  38096. var flat = (options.flat === undefined) ? true : options.flat;
  38097. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38098. var positions = new Array();
  38099. var indices = new Array();
  38100. var normals = new Array();
  38101. var uvs = new Array();
  38102. var colors = new Array();
  38103. var index = 0;
  38104. var faceIdx = 0; // face cursor in the array "indexes"
  38105. var indexes = new Array();
  38106. var i = 0;
  38107. var f = 0;
  38108. var u, v, ang, x, y, tmp;
  38109. // default face colors and UV if undefined
  38110. if (flat) {
  38111. for (f = 0; f < nbfaces; f++) {
  38112. if (faceColors && faceColors[f] === undefined) {
  38113. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38114. }
  38115. if (faceUV && faceUV[f] === undefined) {
  38116. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38117. }
  38118. }
  38119. }
  38120. if (!flat) {
  38121. for (i = 0; i < data.vertex.length; i++) {
  38122. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38123. uvs.push(0, 0);
  38124. }
  38125. for (f = 0; f < nbfaces; f++) {
  38126. for (i = 0; i < data.face[f].length - 2; i++) {
  38127. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38128. }
  38129. }
  38130. }
  38131. else {
  38132. for (f = 0; f < nbfaces; f++) {
  38133. var fl = data.face[f].length; // number of vertices of the current face
  38134. ang = 2 * Math.PI / fl;
  38135. x = 0.5 * Math.tan(ang / 2);
  38136. y = 0.5;
  38137. // positions, uvs, colors
  38138. for (i = 0; i < fl; i++) {
  38139. // positions
  38140. 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);
  38141. indexes.push(index);
  38142. index++;
  38143. // uvs
  38144. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38145. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38146. uvs.push(u, v);
  38147. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38148. y = x * Math.sin(ang) + y * Math.cos(ang);
  38149. x = tmp;
  38150. // colors
  38151. if (faceColors) {
  38152. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38153. }
  38154. }
  38155. // indices from indexes
  38156. for (i = 0; i < fl - 2; i++) {
  38157. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38158. }
  38159. faceIdx += fl;
  38160. }
  38161. }
  38162. VertexData.ComputeNormals(positions, indices, normals);
  38163. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38164. var vertexData = new VertexData();
  38165. vertexData.positions = positions;
  38166. vertexData.indices = indices;
  38167. vertexData.normals = normals;
  38168. vertexData.uvs = uvs;
  38169. if (faceColors && flat) {
  38170. vertexData.colors = colors;
  38171. }
  38172. return vertexData;
  38173. };
  38174. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38175. /**
  38176. * Creates the VertexData for a TorusKnot
  38177. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38178. * * radius the radius of the torus knot, optional, default 2
  38179. * * tube the thickness of the tube, optional, default 0.5
  38180. * * radialSegments the number of sides on each tube segments, optional, default 32
  38181. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38182. * * p the number of windings around the z axis, optional, default 2
  38183. * * q the number of windings around the x axis, optional, default 3
  38184. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38185. * * 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)
  38186. * * 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)
  38187. * @returns the VertexData of the Torus Knot
  38188. */
  38189. VertexData.CreateTorusKnot = function (options) {
  38190. var indices = new Array();
  38191. var positions = new Array();
  38192. var normals = new Array();
  38193. var uvs = new Array();
  38194. var radius = options.radius || 2;
  38195. var tube = options.tube || 0.5;
  38196. var radialSegments = options.radialSegments || 32;
  38197. var tubularSegments = options.tubularSegments || 32;
  38198. var p = options.p || 2;
  38199. var q = options.q || 3;
  38200. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38201. // Helper
  38202. var getPos = function (angle) {
  38203. var cu = Math.cos(angle);
  38204. var su = Math.sin(angle);
  38205. var quOverP = q / p * angle;
  38206. var cs = Math.cos(quOverP);
  38207. var tx = radius * (2 + cs) * 0.5 * cu;
  38208. var ty = radius * (2 + cs) * su * 0.5;
  38209. var tz = radius * Math.sin(quOverP) * 0.5;
  38210. return new BABYLON.Vector3(tx, ty, tz);
  38211. };
  38212. // Vertices
  38213. var i;
  38214. var j;
  38215. for (i = 0; i <= radialSegments; i++) {
  38216. var modI = i % radialSegments;
  38217. var u = modI / radialSegments * 2 * p * Math.PI;
  38218. var p1 = getPos(u);
  38219. var p2 = getPos(u + 0.01);
  38220. var tang = p2.subtract(p1);
  38221. var n = p2.add(p1);
  38222. var bitan = BABYLON.Vector3.Cross(tang, n);
  38223. n = BABYLON.Vector3.Cross(bitan, tang);
  38224. bitan.normalize();
  38225. n.normalize();
  38226. for (j = 0; j < tubularSegments; j++) {
  38227. var modJ = j % tubularSegments;
  38228. var v = modJ / tubularSegments * 2 * Math.PI;
  38229. var cx = -tube * Math.cos(v);
  38230. var cy = tube * Math.sin(v);
  38231. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38232. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38233. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38234. uvs.push(i / radialSegments);
  38235. uvs.push(j / tubularSegments);
  38236. }
  38237. }
  38238. for (i = 0; i < radialSegments; i++) {
  38239. for (j = 0; j < tubularSegments; j++) {
  38240. var jNext = (j + 1) % tubularSegments;
  38241. var a = i * tubularSegments + j;
  38242. var b = (i + 1) * tubularSegments + j;
  38243. var c = (i + 1) * tubularSegments + jNext;
  38244. var d = i * tubularSegments + jNext;
  38245. indices.push(d);
  38246. indices.push(b);
  38247. indices.push(a);
  38248. indices.push(d);
  38249. indices.push(c);
  38250. indices.push(b);
  38251. }
  38252. }
  38253. // Normals
  38254. VertexData.ComputeNormals(positions, indices, normals);
  38255. // Sides
  38256. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38257. // Result
  38258. var vertexData = new VertexData();
  38259. vertexData.indices = indices;
  38260. vertexData.positions = positions;
  38261. vertexData.normals = normals;
  38262. vertexData.uvs = uvs;
  38263. return vertexData;
  38264. };
  38265. // Tools
  38266. /**
  38267. * Compute normals for given positions and indices
  38268. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38269. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38270. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38271. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38272. * * facetNormals : optional array of facet normals (vector3)
  38273. * * facetPositions : optional array of facet positions (vector3)
  38274. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38275. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38276. * * bInfo : optional bounding info, required for facetPartitioning computation
  38277. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38278. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38279. * * useRightHandedSystem: optional boolean to for right handed system computation
  38280. * * depthSort : optional boolean to enable the facet depth sort computation
  38281. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38282. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38283. */
  38284. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38285. // temporary scalar variables
  38286. var index = 0; // facet index
  38287. var p1p2x = 0.0; // p1p2 vector x coordinate
  38288. var p1p2y = 0.0; // p1p2 vector y coordinate
  38289. var p1p2z = 0.0; // p1p2 vector z coordinate
  38290. var p3p2x = 0.0; // p3p2 vector x coordinate
  38291. var p3p2y = 0.0; // p3p2 vector y coordinate
  38292. var p3p2z = 0.0; // p3p2 vector z coordinate
  38293. var faceNormalx = 0.0; // facet normal x coordinate
  38294. var faceNormaly = 0.0; // facet normal y coordinate
  38295. var faceNormalz = 0.0; // facet normal z coordinate
  38296. var length = 0.0; // facet normal length before normalization
  38297. var v1x = 0; // vector1 x index in the positions array
  38298. var v1y = 0; // vector1 y index in the positions array
  38299. var v1z = 0; // vector1 z index in the positions array
  38300. var v2x = 0; // vector2 x index in the positions array
  38301. var v2y = 0; // vector2 y index in the positions array
  38302. var v2z = 0; // vector2 z index in the positions array
  38303. var v3x = 0; // vector3 x index in the positions array
  38304. var v3y = 0; // vector3 y index in the positions array
  38305. var v3z = 0; // vector3 z index in the positions array
  38306. var computeFacetNormals = false;
  38307. var computeFacetPositions = false;
  38308. var computeFacetPartitioning = false;
  38309. var computeDepthSort = false;
  38310. var faceNormalSign = 1;
  38311. var ratio = 0;
  38312. var distanceTo = null;
  38313. if (options) {
  38314. computeFacetNormals = (options.facetNormals) ? true : false;
  38315. computeFacetPositions = (options.facetPositions) ? true : false;
  38316. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38317. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38318. ratio = options.ratio || 0;
  38319. computeDepthSort = (options.depthSort) ? true : false;
  38320. distanceTo = (options.distanceTo);
  38321. if (computeDepthSort) {
  38322. if (distanceTo === undefined) {
  38323. distanceTo = BABYLON.Vector3.Zero();
  38324. }
  38325. var depthSortedFacets = options.depthSortedFacets;
  38326. }
  38327. }
  38328. // facetPartitioning reinit if needed
  38329. var xSubRatio = 0;
  38330. var ySubRatio = 0;
  38331. var zSubRatio = 0;
  38332. var subSq = 0;
  38333. if (computeFacetPartitioning && options && options.bbSize) {
  38334. var ox = 0; // X partitioning index for facet position
  38335. var oy = 0; // Y partinioning index for facet position
  38336. var oz = 0; // Z partinioning index for facet position
  38337. var b1x = 0; // X partitioning index for facet v1 vertex
  38338. var b1y = 0; // Y partitioning index for facet v1 vertex
  38339. var b1z = 0; // z partitioning index for facet v1 vertex
  38340. var b2x = 0; // X partitioning index for facet v2 vertex
  38341. var b2y = 0; // Y partitioning index for facet v2 vertex
  38342. var b2z = 0; // Z partitioning index for facet v2 vertex
  38343. var b3x = 0; // X partitioning index for facet v3 vertex
  38344. var b3y = 0; // Y partitioning index for facet v3 vertex
  38345. var b3z = 0; // Z partitioning index for facet v3 vertex
  38346. var block_idx_o = 0; // facet barycenter block index
  38347. var block_idx_v1 = 0; // v1 vertex block index
  38348. var block_idx_v2 = 0; // v2 vertex block index
  38349. var block_idx_v3 = 0; // v3 vertex block index
  38350. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38351. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38352. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38353. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38354. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38355. subSq = options.subDiv.max * options.subDiv.max;
  38356. options.facetPartitioning.length = 0;
  38357. }
  38358. // reset the normals
  38359. for (index = 0; index < positions.length; index++) {
  38360. normals[index] = 0.0;
  38361. }
  38362. // Loop : 1 indice triplet = 1 facet
  38363. var nbFaces = (indices.length / 3) | 0;
  38364. for (index = 0; index < nbFaces; index++) {
  38365. // get the indexes of the coordinates of each vertex of the facet
  38366. v1x = indices[index * 3] * 3;
  38367. v1y = v1x + 1;
  38368. v1z = v1x + 2;
  38369. v2x = indices[index * 3 + 1] * 3;
  38370. v2y = v2x + 1;
  38371. v2z = v2x + 2;
  38372. v3x = indices[index * 3 + 2] * 3;
  38373. v3y = v3x + 1;
  38374. v3z = v3x + 2;
  38375. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38376. p1p2y = positions[v1y] - positions[v2y];
  38377. p1p2z = positions[v1z] - positions[v2z];
  38378. p3p2x = positions[v3x] - positions[v2x];
  38379. p3p2y = positions[v3y] - positions[v2y];
  38380. p3p2z = positions[v3z] - positions[v2z];
  38381. // compute the face normal with the cross product
  38382. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38383. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38384. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38385. // normalize this normal and store it in the array facetData
  38386. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38387. length = (length === 0) ? 1.0 : length;
  38388. faceNormalx /= length;
  38389. faceNormaly /= length;
  38390. faceNormalz /= length;
  38391. if (computeFacetNormals && options) {
  38392. options.facetNormals[index].x = faceNormalx;
  38393. options.facetNormals[index].y = faceNormaly;
  38394. options.facetNormals[index].z = faceNormalz;
  38395. }
  38396. if (computeFacetPositions && options) {
  38397. // compute and the facet barycenter coordinates in the array facetPositions
  38398. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38399. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38400. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38401. }
  38402. if (computeFacetPartitioning && options) {
  38403. // store the facet indexes in arrays in the main facetPartitioning array :
  38404. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38405. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38406. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38407. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38408. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38409. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38410. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38411. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38412. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38413. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38414. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38415. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38416. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38417. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38418. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38419. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38420. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38421. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38422. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38423. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38424. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38425. // push each facet index in each block containing the vertex
  38426. options.facetPartitioning[block_idx_v1].push(index);
  38427. if (block_idx_v2 != block_idx_v1) {
  38428. options.facetPartitioning[block_idx_v2].push(index);
  38429. }
  38430. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38431. options.facetPartitioning[block_idx_v3].push(index);
  38432. }
  38433. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38434. options.facetPartitioning[block_idx_o].push(index);
  38435. }
  38436. }
  38437. if (computeDepthSort && options && options.facetPositions) {
  38438. var dsf = depthSortedFacets[index];
  38439. dsf.ind = index * 3;
  38440. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38441. }
  38442. // compute the normals anyway
  38443. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38444. normals[v1y] += faceNormaly;
  38445. normals[v1z] += faceNormalz;
  38446. normals[v2x] += faceNormalx;
  38447. normals[v2y] += faceNormaly;
  38448. normals[v2z] += faceNormalz;
  38449. normals[v3x] += faceNormalx;
  38450. normals[v3y] += faceNormaly;
  38451. normals[v3z] += faceNormalz;
  38452. }
  38453. // last normalization of each normal
  38454. for (index = 0; index < normals.length / 3; index++) {
  38455. faceNormalx = normals[index * 3];
  38456. faceNormaly = normals[index * 3 + 1];
  38457. faceNormalz = normals[index * 3 + 2];
  38458. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38459. length = (length === 0) ? 1.0 : length;
  38460. faceNormalx /= length;
  38461. faceNormaly /= length;
  38462. faceNormalz /= length;
  38463. normals[index * 3] = faceNormalx;
  38464. normals[index * 3 + 1] = faceNormaly;
  38465. normals[index * 3 + 2] = faceNormalz;
  38466. }
  38467. };
  38468. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38469. var li = indices.length;
  38470. var ln = normals.length;
  38471. var i;
  38472. var n;
  38473. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38474. switch (sideOrientation) {
  38475. case BABYLON.Mesh.FRONTSIDE:
  38476. // nothing changed
  38477. break;
  38478. case BABYLON.Mesh.BACKSIDE:
  38479. var tmp;
  38480. // indices
  38481. for (i = 0; i < li; i += 3) {
  38482. tmp = indices[i];
  38483. indices[i] = indices[i + 2];
  38484. indices[i + 2] = tmp;
  38485. }
  38486. // normals
  38487. for (n = 0; n < ln; n++) {
  38488. normals[n] = -normals[n];
  38489. }
  38490. break;
  38491. case BABYLON.Mesh.DOUBLESIDE:
  38492. // positions
  38493. var lp = positions.length;
  38494. var l = lp / 3;
  38495. for (var p = 0; p < lp; p++) {
  38496. positions[lp + p] = positions[p];
  38497. }
  38498. // indices
  38499. for (i = 0; i < li; i += 3) {
  38500. indices[i + li] = indices[i + 2] + l;
  38501. indices[i + 1 + li] = indices[i + 1] + l;
  38502. indices[i + 2 + li] = indices[i] + l;
  38503. }
  38504. // normals
  38505. for (n = 0; n < ln; n++) {
  38506. normals[ln + n] = -normals[n];
  38507. }
  38508. // uvs
  38509. var lu = uvs.length;
  38510. var u = 0;
  38511. for (u = 0; u < lu; u++) {
  38512. uvs[u + lu] = uvs[u];
  38513. }
  38514. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38515. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38516. u = 0;
  38517. for (i = 0; i < lu / 2; i++) {
  38518. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38519. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38520. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38521. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38522. u += 2;
  38523. }
  38524. break;
  38525. }
  38526. };
  38527. /**
  38528. * Applies VertexData created from the imported parameters to the geometry
  38529. * @param parsedVertexData the parsed data from an imported file
  38530. * @param geometry the geometry to apply the VertexData to
  38531. */
  38532. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38533. var vertexData = new VertexData();
  38534. // positions
  38535. var positions = parsedVertexData.positions;
  38536. if (positions) {
  38537. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38538. }
  38539. // normals
  38540. var normals = parsedVertexData.normals;
  38541. if (normals) {
  38542. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38543. }
  38544. // tangents
  38545. var tangents = parsedVertexData.tangents;
  38546. if (tangents) {
  38547. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38548. }
  38549. // uvs
  38550. var uvs = parsedVertexData.uvs;
  38551. if (uvs) {
  38552. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38553. }
  38554. // uv2s
  38555. var uv2s = parsedVertexData.uv2s;
  38556. if (uv2s) {
  38557. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38558. }
  38559. // uv3s
  38560. var uv3s = parsedVertexData.uv3s;
  38561. if (uv3s) {
  38562. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38563. }
  38564. // uv4s
  38565. var uv4s = parsedVertexData.uv4s;
  38566. if (uv4s) {
  38567. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38568. }
  38569. // uv5s
  38570. var uv5s = parsedVertexData.uv5s;
  38571. if (uv5s) {
  38572. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38573. }
  38574. // uv6s
  38575. var uv6s = parsedVertexData.uv6s;
  38576. if (uv6s) {
  38577. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38578. }
  38579. // colors
  38580. var colors = parsedVertexData.colors;
  38581. if (colors) {
  38582. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38583. }
  38584. // matricesIndices
  38585. var matricesIndices = parsedVertexData.matricesIndices;
  38586. if (matricesIndices) {
  38587. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38588. }
  38589. // matricesWeights
  38590. var matricesWeights = parsedVertexData.matricesWeights;
  38591. if (matricesWeights) {
  38592. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38593. }
  38594. // indices
  38595. var indices = parsedVertexData.indices;
  38596. if (indices) {
  38597. vertexData.indices = indices;
  38598. }
  38599. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38600. };
  38601. return VertexData;
  38602. }());
  38603. BABYLON.VertexData = VertexData;
  38604. })(BABYLON || (BABYLON = {}));
  38605. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38606. var BABYLON;
  38607. (function (BABYLON) {
  38608. /**
  38609. * Class used to store geometry data (vertex buffers + index buffer)
  38610. */
  38611. var Geometry = /** @class */ (function () {
  38612. /**
  38613. * Creates a new geometry
  38614. * @param id defines the unique ID
  38615. * @param scene defines the hosting scene
  38616. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38617. * @param updatable defines if geometry must be updatable (false by default)
  38618. * @param mesh defines the mesh that will be associated with the geometry
  38619. */
  38620. function Geometry(id, scene, vertexData, updatable, mesh) {
  38621. if (updatable === void 0) { updatable = false; }
  38622. if (mesh === void 0) { mesh = null; }
  38623. /**
  38624. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38625. */
  38626. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38627. this._totalVertices = 0;
  38628. this._isDisposed = false;
  38629. this._indexBufferIsUpdatable = false;
  38630. this.id = id;
  38631. this._engine = scene.getEngine();
  38632. this._meshes = [];
  38633. this._scene = scene;
  38634. //Init vertex buffer cache
  38635. this._vertexBuffers = {};
  38636. this._indices = [];
  38637. this._updatable = updatable;
  38638. // vertexData
  38639. if (vertexData) {
  38640. this.setAllVerticesData(vertexData, updatable);
  38641. }
  38642. else {
  38643. this._totalVertices = 0;
  38644. this._indices = [];
  38645. }
  38646. if (this._engine.getCaps().vertexArrayObject) {
  38647. this._vertexArrayObjects = {};
  38648. }
  38649. // applyToMesh
  38650. if (mesh) {
  38651. if (mesh.getClassName() === "LinesMesh") {
  38652. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38653. this._updateExtend();
  38654. }
  38655. this.applyToMesh(mesh);
  38656. mesh.computeWorldMatrix(true);
  38657. }
  38658. }
  38659. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38660. /**
  38661. * 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
  38662. */
  38663. get: function () {
  38664. return this._boundingBias;
  38665. },
  38666. /**
  38667. * 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
  38668. */
  38669. set: function (value) {
  38670. if (this._boundingBias && this._boundingBias.equals(value)) {
  38671. return;
  38672. }
  38673. this._boundingBias = value.clone();
  38674. this._updateBoundingInfo(true, null);
  38675. },
  38676. enumerable: true,
  38677. configurable: true
  38678. });
  38679. /**
  38680. * Static function used to attach a new empty geometry to a mesh
  38681. * @param mesh defines the mesh to attach the geometry to
  38682. * @returns the new {BABYLON.Geometry}
  38683. */
  38684. Geometry.CreateGeometryForMesh = function (mesh) {
  38685. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38686. geometry.applyToMesh(mesh);
  38687. return geometry;
  38688. };
  38689. Object.defineProperty(Geometry.prototype, "extend", {
  38690. /**
  38691. * Gets the current extend of the geometry
  38692. */
  38693. get: function () {
  38694. return this._extend;
  38695. },
  38696. enumerable: true,
  38697. configurable: true
  38698. });
  38699. /**
  38700. * Gets the hosting scene
  38701. * @returns the hosting {BABYLON.Scene}
  38702. */
  38703. Geometry.prototype.getScene = function () {
  38704. return this._scene;
  38705. };
  38706. /**
  38707. * Gets the hosting engine
  38708. * @returns the hosting {BABYLON.Engine}
  38709. */
  38710. Geometry.prototype.getEngine = function () {
  38711. return this._engine;
  38712. };
  38713. /**
  38714. * Defines if the geometry is ready to use
  38715. * @returns true if the geometry is ready to be used
  38716. */
  38717. Geometry.prototype.isReady = function () {
  38718. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38719. };
  38720. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38721. /**
  38722. * Gets a value indicating that the geometry should not be serialized
  38723. */
  38724. get: function () {
  38725. for (var index = 0; index < this._meshes.length; index++) {
  38726. if (!this._meshes[index].doNotSerialize) {
  38727. return false;
  38728. }
  38729. }
  38730. return true;
  38731. },
  38732. enumerable: true,
  38733. configurable: true
  38734. });
  38735. /** @hidden */
  38736. Geometry.prototype._rebuild = function () {
  38737. if (this._vertexArrayObjects) {
  38738. this._vertexArrayObjects = {};
  38739. }
  38740. // Index buffer
  38741. if (this._meshes.length !== 0 && this._indices) {
  38742. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38743. }
  38744. // Vertex buffers
  38745. for (var key in this._vertexBuffers) {
  38746. var vertexBuffer = this._vertexBuffers[key];
  38747. vertexBuffer._rebuild();
  38748. }
  38749. };
  38750. /**
  38751. * Affects all geometry data in one call
  38752. * @param vertexData defines the geometry data
  38753. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38754. */
  38755. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38756. vertexData.applyToGeometry(this, updatable);
  38757. this.notifyUpdate();
  38758. };
  38759. /**
  38760. * Set specific vertex data
  38761. * @param kind defines the data kind (Position, normal, etc...)
  38762. * @param data defines the vertex data to use
  38763. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38764. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38765. */
  38766. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38767. if (updatable === void 0) { updatable = false; }
  38768. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38769. this.setVerticesBuffer(buffer);
  38770. };
  38771. /**
  38772. * Removes a specific vertex data
  38773. * @param kind defines the data kind (Position, normal, etc...)
  38774. */
  38775. Geometry.prototype.removeVerticesData = function (kind) {
  38776. if (this._vertexBuffers[kind]) {
  38777. this._vertexBuffers[kind].dispose();
  38778. delete this._vertexBuffers[kind];
  38779. }
  38780. };
  38781. /**
  38782. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38783. * @param buffer defines the vertex buffer to use
  38784. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38785. */
  38786. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38787. if (totalVertices === void 0) { totalVertices = null; }
  38788. var kind = buffer.getKind();
  38789. if (this._vertexBuffers[kind]) {
  38790. this._vertexBuffers[kind].dispose();
  38791. }
  38792. this._vertexBuffers[kind] = buffer;
  38793. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38794. var data = buffer.getData();
  38795. if (totalVertices != null) {
  38796. this._totalVertices = totalVertices;
  38797. }
  38798. else {
  38799. if (data != null) {
  38800. this._totalVertices = data.length / (buffer.byteStride / 4);
  38801. }
  38802. }
  38803. this._updateExtend(data);
  38804. this._resetPointsArrayCache();
  38805. var meshes = this._meshes;
  38806. var numOfMeshes = meshes.length;
  38807. for (var index = 0; index < numOfMeshes; index++) {
  38808. var mesh = meshes[index];
  38809. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38810. mesh._createGlobalSubMesh(false);
  38811. mesh.computeWorldMatrix(true);
  38812. }
  38813. }
  38814. this.notifyUpdate(kind);
  38815. if (this._vertexArrayObjects) {
  38816. this._disposeVertexArrayObjects();
  38817. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38818. }
  38819. };
  38820. /**
  38821. * Update a specific vertex buffer
  38822. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38823. * It will do nothing if the buffer is not updatable
  38824. * @param kind defines the data kind (Position, normal, etc...)
  38825. * @param data defines the data to use
  38826. * @param offset defines the offset in the target buffer where to store the data
  38827. * @param useBytes set to true if the offset is in bytes
  38828. */
  38829. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38830. if (useBytes === void 0) { useBytes = false; }
  38831. var vertexBuffer = this.getVertexBuffer(kind);
  38832. if (!vertexBuffer) {
  38833. return;
  38834. }
  38835. vertexBuffer.updateDirectly(data, offset, useBytes);
  38836. this.notifyUpdate(kind);
  38837. };
  38838. /**
  38839. * Update a specific vertex buffer
  38840. * This function will create a new buffer if the current one is not updatable
  38841. * @param kind defines the data kind (Position, normal, etc...)
  38842. * @param data defines the data to use
  38843. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38844. */
  38845. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38846. if (updateExtends === void 0) { updateExtends = false; }
  38847. var vertexBuffer = this.getVertexBuffer(kind);
  38848. if (!vertexBuffer) {
  38849. return;
  38850. }
  38851. vertexBuffer.update(data);
  38852. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38853. this._updateBoundingInfo(updateExtends, data);
  38854. }
  38855. this.notifyUpdate(kind);
  38856. };
  38857. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38858. if (updateExtends) {
  38859. this._updateExtend(data);
  38860. }
  38861. var meshes = this._meshes;
  38862. var numOfMeshes = meshes.length;
  38863. this._resetPointsArrayCache();
  38864. for (var index = 0; index < numOfMeshes; index++) {
  38865. var mesh = meshes[index];
  38866. if (updateExtends) {
  38867. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38868. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38869. var subMesh = mesh.subMeshes[subIndex];
  38870. subMesh.refreshBoundingInfo();
  38871. }
  38872. }
  38873. }
  38874. };
  38875. /** @hidden */
  38876. Geometry.prototype._bind = function (effect, indexToBind) {
  38877. if (!effect) {
  38878. return;
  38879. }
  38880. if (indexToBind === undefined) {
  38881. indexToBind = this._indexBuffer;
  38882. }
  38883. var vbs = this.getVertexBuffers();
  38884. if (!vbs) {
  38885. return;
  38886. }
  38887. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38888. this._engine.bindBuffers(vbs, indexToBind, effect);
  38889. return;
  38890. }
  38891. // Using VAO
  38892. if (!this._vertexArrayObjects[effect.key]) {
  38893. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38894. }
  38895. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38896. };
  38897. /**
  38898. * Gets total number of vertices
  38899. * @returns the total number of vertices
  38900. */
  38901. Geometry.prototype.getTotalVertices = function () {
  38902. if (!this.isReady()) {
  38903. return 0;
  38904. }
  38905. return this._totalVertices;
  38906. };
  38907. /**
  38908. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38909. * @param kind defines the data kind (Position, normal, etc...)
  38910. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38911. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38912. * @returns a float array containing vertex data
  38913. */
  38914. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38915. var vertexBuffer = this.getVertexBuffer(kind);
  38916. if (!vertexBuffer) {
  38917. return null;
  38918. }
  38919. var data = vertexBuffer.getData();
  38920. if (!data) {
  38921. return null;
  38922. }
  38923. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38924. var count = this._totalVertices * vertexBuffer.getSize();
  38925. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38926. var copy_1 = new Array(count);
  38927. vertexBuffer.forEach(count, function (value, index) {
  38928. copy_1[index] = value;
  38929. });
  38930. return copy_1;
  38931. }
  38932. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38933. if (data instanceof Array) {
  38934. var offset = vertexBuffer.byteOffset / 4;
  38935. return BABYLON.Tools.Slice(data, offset, offset + count);
  38936. }
  38937. else if (data instanceof ArrayBuffer) {
  38938. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38939. }
  38940. else {
  38941. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38942. }
  38943. }
  38944. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38945. return BABYLON.Tools.Slice(data);
  38946. }
  38947. return data;
  38948. };
  38949. /**
  38950. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38951. * @param kind defines the data kind (Position, normal, etc...)
  38952. * @returns true if the vertex buffer with the specified kind is updatable
  38953. */
  38954. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38955. var vb = this._vertexBuffers[kind];
  38956. if (!vb) {
  38957. return false;
  38958. }
  38959. return vb.isUpdatable();
  38960. };
  38961. /**
  38962. * Gets a specific vertex buffer
  38963. * @param kind defines the data kind (Position, normal, etc...)
  38964. * @returns a {BABYLON.VertexBuffer}
  38965. */
  38966. Geometry.prototype.getVertexBuffer = function (kind) {
  38967. if (!this.isReady()) {
  38968. return null;
  38969. }
  38970. return this._vertexBuffers[kind];
  38971. };
  38972. /**
  38973. * Returns all vertex buffers
  38974. * @return an object holding all vertex buffers indexed by kind
  38975. */
  38976. Geometry.prototype.getVertexBuffers = function () {
  38977. if (!this.isReady()) {
  38978. return null;
  38979. }
  38980. return this._vertexBuffers;
  38981. };
  38982. /**
  38983. * Gets a boolean indicating if specific vertex buffer is present
  38984. * @param kind defines the data kind (Position, normal, etc...)
  38985. * @returns true if data is present
  38986. */
  38987. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38988. if (!this._vertexBuffers) {
  38989. if (this._delayInfo) {
  38990. return this._delayInfo.indexOf(kind) !== -1;
  38991. }
  38992. return false;
  38993. }
  38994. return this._vertexBuffers[kind] !== undefined;
  38995. };
  38996. /**
  38997. * Gets a list of all attached data kinds (Position, normal, etc...)
  38998. * @returns a list of string containing all kinds
  38999. */
  39000. Geometry.prototype.getVerticesDataKinds = function () {
  39001. var result = [];
  39002. var kind;
  39003. if (!this._vertexBuffers && this._delayInfo) {
  39004. for (kind in this._delayInfo) {
  39005. result.push(kind);
  39006. }
  39007. }
  39008. else {
  39009. for (kind in this._vertexBuffers) {
  39010. result.push(kind);
  39011. }
  39012. }
  39013. return result;
  39014. };
  39015. /**
  39016. * Update index buffer
  39017. * @param indices defines the indices to store in the index buffer
  39018. * @param offset defines the offset in the target buffer where to store the data
  39019. */
  39020. Geometry.prototype.updateIndices = function (indices, offset) {
  39021. if (!this._indexBuffer) {
  39022. return;
  39023. }
  39024. if (!this._indexBufferIsUpdatable) {
  39025. this.setIndices(indices, null, true);
  39026. }
  39027. else {
  39028. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39029. }
  39030. };
  39031. /**
  39032. * Creates a new index buffer
  39033. * @param indices defines the indices to store in the index buffer
  39034. * @param totalVertices defines the total number of vertices (could be null)
  39035. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39036. */
  39037. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39038. if (totalVertices === void 0) { totalVertices = null; }
  39039. if (updatable === void 0) { updatable = false; }
  39040. if (this._indexBuffer) {
  39041. this._engine._releaseBuffer(this._indexBuffer);
  39042. }
  39043. this._disposeVertexArrayObjects();
  39044. this._indices = indices;
  39045. this._indexBufferIsUpdatable = updatable;
  39046. if (this._meshes.length !== 0 && this._indices) {
  39047. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39048. }
  39049. if (totalVertices != undefined) { // including null and undefined
  39050. this._totalVertices = totalVertices;
  39051. }
  39052. var meshes = this._meshes;
  39053. var numOfMeshes = meshes.length;
  39054. for (var index = 0; index < numOfMeshes; index++) {
  39055. meshes[index]._createGlobalSubMesh(true);
  39056. }
  39057. this.notifyUpdate();
  39058. };
  39059. /**
  39060. * Return the total number of indices
  39061. * @returns the total number of indices
  39062. */
  39063. Geometry.prototype.getTotalIndices = function () {
  39064. if (!this.isReady()) {
  39065. return 0;
  39066. }
  39067. return this._indices.length;
  39068. };
  39069. /**
  39070. * Gets the index buffer array
  39071. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39072. * @returns the index buffer array
  39073. */
  39074. Geometry.prototype.getIndices = function (copyWhenShared) {
  39075. if (!this.isReady()) {
  39076. return null;
  39077. }
  39078. var orig = this._indices;
  39079. if (!copyWhenShared || this._meshes.length === 1) {
  39080. return orig;
  39081. }
  39082. else {
  39083. var len = orig.length;
  39084. var copy = [];
  39085. for (var i = 0; i < len; i++) {
  39086. copy.push(orig[i]);
  39087. }
  39088. return copy;
  39089. }
  39090. };
  39091. /**
  39092. * Gets the index buffer
  39093. * @return the index buffer
  39094. */
  39095. Geometry.prototype.getIndexBuffer = function () {
  39096. if (!this.isReady()) {
  39097. return null;
  39098. }
  39099. return this._indexBuffer;
  39100. };
  39101. /** @hidden */
  39102. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39103. if (effect === void 0) { effect = null; }
  39104. if (!effect || !this._vertexArrayObjects) {
  39105. return;
  39106. }
  39107. if (this._vertexArrayObjects[effect.key]) {
  39108. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39109. delete this._vertexArrayObjects[effect.key];
  39110. }
  39111. };
  39112. /**
  39113. * Release the associated resources for a specific mesh
  39114. * @param mesh defines the source mesh
  39115. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39116. */
  39117. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39118. var meshes = this._meshes;
  39119. var index = meshes.indexOf(mesh);
  39120. if (index === -1) {
  39121. return;
  39122. }
  39123. meshes.splice(index, 1);
  39124. mesh._geometry = null;
  39125. if (meshes.length === 0 && shouldDispose) {
  39126. this.dispose();
  39127. }
  39128. };
  39129. /**
  39130. * Apply current geometry to a given mesh
  39131. * @param mesh defines the mesh to apply geometry to
  39132. */
  39133. Geometry.prototype.applyToMesh = function (mesh) {
  39134. if (mesh._geometry === this) {
  39135. return;
  39136. }
  39137. var previousGeometry = mesh._geometry;
  39138. if (previousGeometry) {
  39139. previousGeometry.releaseForMesh(mesh);
  39140. }
  39141. var meshes = this._meshes;
  39142. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39143. mesh._geometry = this;
  39144. this._scene.pushGeometry(this);
  39145. meshes.push(mesh);
  39146. if (this.isReady()) {
  39147. this._applyToMesh(mesh);
  39148. }
  39149. else {
  39150. mesh._boundingInfo = this._boundingInfo;
  39151. }
  39152. };
  39153. Geometry.prototype._updateExtend = function (data) {
  39154. if (data === void 0) { data = null; }
  39155. if (!data) {
  39156. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39157. }
  39158. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39159. };
  39160. Geometry.prototype._applyToMesh = function (mesh) {
  39161. var numOfMeshes = this._meshes.length;
  39162. // vertexBuffers
  39163. for (var kind in this._vertexBuffers) {
  39164. if (numOfMeshes === 1) {
  39165. this._vertexBuffers[kind].create();
  39166. }
  39167. var buffer = this._vertexBuffers[kind].getBuffer();
  39168. if (buffer)
  39169. buffer.references = numOfMeshes;
  39170. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39171. if (!this._extend) {
  39172. this._updateExtend();
  39173. }
  39174. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39175. mesh._createGlobalSubMesh(false);
  39176. //bounding info was just created again, world matrix should be applied again.
  39177. mesh._updateBoundingInfo();
  39178. }
  39179. }
  39180. // indexBuffer
  39181. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39182. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39183. }
  39184. if (this._indexBuffer) {
  39185. this._indexBuffer.references = numOfMeshes;
  39186. }
  39187. };
  39188. Geometry.prototype.notifyUpdate = function (kind) {
  39189. if (this.onGeometryUpdated) {
  39190. this.onGeometryUpdated(this, kind);
  39191. }
  39192. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39193. var mesh = _a[_i];
  39194. mesh._markSubMeshesAsAttributesDirty();
  39195. }
  39196. };
  39197. /**
  39198. * Load the geometry if it was flagged as delay loaded
  39199. * @param scene defines the hosting scene
  39200. * @param onLoaded defines a callback called when the geometry is loaded
  39201. */
  39202. Geometry.prototype.load = function (scene, onLoaded) {
  39203. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39204. return;
  39205. }
  39206. if (this.isReady()) {
  39207. if (onLoaded) {
  39208. onLoaded();
  39209. }
  39210. return;
  39211. }
  39212. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39213. this._queueLoad(scene, onLoaded);
  39214. };
  39215. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39216. var _this = this;
  39217. if (!this.delayLoadingFile) {
  39218. return;
  39219. }
  39220. scene._addPendingData(this);
  39221. scene._loadFile(this.delayLoadingFile, function (data) {
  39222. if (!_this._delayLoadingFunction) {
  39223. return;
  39224. }
  39225. _this._delayLoadingFunction(JSON.parse(data), _this);
  39226. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39227. _this._delayInfo = [];
  39228. scene._removePendingData(_this);
  39229. var meshes = _this._meshes;
  39230. var numOfMeshes = meshes.length;
  39231. for (var index = 0; index < numOfMeshes; index++) {
  39232. _this._applyToMesh(meshes[index]);
  39233. }
  39234. if (onLoaded) {
  39235. onLoaded();
  39236. }
  39237. }, undefined, true);
  39238. };
  39239. /**
  39240. * Invert the geometry to move from a right handed system to a left handed one.
  39241. */
  39242. Geometry.prototype.toLeftHanded = function () {
  39243. // Flip faces
  39244. var tIndices = this.getIndices(false);
  39245. if (tIndices != null && tIndices.length > 0) {
  39246. for (var i = 0; i < tIndices.length; i += 3) {
  39247. var tTemp = tIndices[i + 0];
  39248. tIndices[i + 0] = tIndices[i + 2];
  39249. tIndices[i + 2] = tTemp;
  39250. }
  39251. this.setIndices(tIndices);
  39252. }
  39253. // Negate position.z
  39254. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39255. if (tPositions != null && tPositions.length > 0) {
  39256. for (var i = 0; i < tPositions.length; i += 3) {
  39257. tPositions[i + 2] = -tPositions[i + 2];
  39258. }
  39259. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39260. }
  39261. // Negate normal.z
  39262. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39263. if (tNormals != null && tNormals.length > 0) {
  39264. for (var i = 0; i < tNormals.length; i += 3) {
  39265. tNormals[i + 2] = -tNormals[i + 2];
  39266. }
  39267. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39268. }
  39269. };
  39270. // Cache
  39271. /** @hidden */
  39272. Geometry.prototype._resetPointsArrayCache = function () {
  39273. this._positions = null;
  39274. };
  39275. /** @hidden */
  39276. Geometry.prototype._generatePointsArray = function () {
  39277. if (this._positions)
  39278. return true;
  39279. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39280. if (!data || data.length === 0) {
  39281. return false;
  39282. }
  39283. this._positions = [];
  39284. for (var index = 0; index < data.length; index += 3) {
  39285. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39286. }
  39287. return true;
  39288. };
  39289. /**
  39290. * Gets a value indicating if the geometry is disposed
  39291. * @returns true if the geometry was disposed
  39292. */
  39293. Geometry.prototype.isDisposed = function () {
  39294. return this._isDisposed;
  39295. };
  39296. Geometry.prototype._disposeVertexArrayObjects = function () {
  39297. if (this._vertexArrayObjects) {
  39298. for (var kind in this._vertexArrayObjects) {
  39299. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39300. }
  39301. this._vertexArrayObjects = {};
  39302. }
  39303. };
  39304. /**
  39305. * Free all associated resources
  39306. */
  39307. Geometry.prototype.dispose = function () {
  39308. var meshes = this._meshes;
  39309. var numOfMeshes = meshes.length;
  39310. var index;
  39311. for (index = 0; index < numOfMeshes; index++) {
  39312. this.releaseForMesh(meshes[index]);
  39313. }
  39314. this._meshes = [];
  39315. this._disposeVertexArrayObjects();
  39316. for (var kind in this._vertexBuffers) {
  39317. this._vertexBuffers[kind].dispose();
  39318. }
  39319. this._vertexBuffers = {};
  39320. this._totalVertices = 0;
  39321. if (this._indexBuffer) {
  39322. this._engine._releaseBuffer(this._indexBuffer);
  39323. }
  39324. this._indexBuffer = null;
  39325. this._indices = [];
  39326. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39327. this.delayLoadingFile = null;
  39328. this._delayLoadingFunction = null;
  39329. this._delayInfo = [];
  39330. this._boundingInfo = null;
  39331. this._scene.removeGeometry(this);
  39332. this._isDisposed = true;
  39333. };
  39334. /**
  39335. * Clone the current geometry into a new geometry
  39336. * @param id defines the unique ID of the new geometry
  39337. * @returns a new geometry object
  39338. */
  39339. Geometry.prototype.copy = function (id) {
  39340. var vertexData = new BABYLON.VertexData();
  39341. vertexData.indices = [];
  39342. var indices = this.getIndices();
  39343. if (indices) {
  39344. for (var index = 0; index < indices.length; index++) {
  39345. vertexData.indices.push(indices[index]);
  39346. }
  39347. }
  39348. var updatable = false;
  39349. var stopChecking = false;
  39350. var kind;
  39351. for (kind in this._vertexBuffers) {
  39352. // using slice() to make a copy of the array and not just reference it
  39353. var data = this.getVerticesData(kind);
  39354. if (data instanceof Float32Array) {
  39355. vertexData.set(new Float32Array(data), kind);
  39356. }
  39357. else {
  39358. vertexData.set(data.slice(0), kind);
  39359. }
  39360. if (!stopChecking) {
  39361. var vb = this.getVertexBuffer(kind);
  39362. if (vb) {
  39363. updatable = vb.isUpdatable();
  39364. stopChecking = !updatable;
  39365. }
  39366. }
  39367. }
  39368. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39369. geometry.delayLoadState = this.delayLoadState;
  39370. geometry.delayLoadingFile = this.delayLoadingFile;
  39371. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39372. for (kind in this._delayInfo) {
  39373. geometry._delayInfo = geometry._delayInfo || [];
  39374. geometry._delayInfo.push(kind);
  39375. }
  39376. // Bounding info
  39377. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39378. return geometry;
  39379. };
  39380. /**
  39381. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39382. * @return a JSON representation of the current geometry data (without the vertices data)
  39383. */
  39384. Geometry.prototype.serialize = function () {
  39385. var serializationObject = {};
  39386. serializationObject.id = this.id;
  39387. serializationObject.updatable = this._updatable;
  39388. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39389. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39390. }
  39391. return serializationObject;
  39392. };
  39393. Geometry.prototype.toNumberArray = function (origin) {
  39394. if (Array.isArray(origin)) {
  39395. return origin;
  39396. }
  39397. else {
  39398. return Array.prototype.slice.call(origin);
  39399. }
  39400. };
  39401. /**
  39402. * Serialize all vertices data into a JSON oject
  39403. * @returns a JSON representation of the current geometry data
  39404. */
  39405. Geometry.prototype.serializeVerticeData = function () {
  39406. var serializationObject = this.serialize();
  39407. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39408. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39409. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39410. serializationObject.positions._updatable = true;
  39411. }
  39412. }
  39413. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39414. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39415. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39416. serializationObject.normals._updatable = true;
  39417. }
  39418. }
  39419. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39420. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39421. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39422. serializationObject.tangets._updatable = true;
  39423. }
  39424. }
  39425. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39426. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39427. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39428. serializationObject.uvs._updatable = true;
  39429. }
  39430. }
  39431. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39432. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39433. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39434. serializationObject.uv2s._updatable = true;
  39435. }
  39436. }
  39437. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39438. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39439. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39440. serializationObject.uv3s._updatable = true;
  39441. }
  39442. }
  39443. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39444. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39445. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39446. serializationObject.uv4s._updatable = true;
  39447. }
  39448. }
  39449. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39450. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39451. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39452. serializationObject.uv5s._updatable = true;
  39453. }
  39454. }
  39455. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39456. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39457. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39458. serializationObject.uv6s._updatable = true;
  39459. }
  39460. }
  39461. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39462. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39463. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39464. serializationObject.colors._updatable = true;
  39465. }
  39466. }
  39467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39468. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39469. serializationObject.matricesIndices._isExpanded = true;
  39470. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39471. serializationObject.matricesIndices._updatable = true;
  39472. }
  39473. }
  39474. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39475. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39476. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39477. serializationObject.matricesWeights._updatable = true;
  39478. }
  39479. }
  39480. serializationObject.indices = this.toNumberArray(this.getIndices());
  39481. return serializationObject;
  39482. };
  39483. // Statics
  39484. /**
  39485. * Extracts a clone of a mesh geometry
  39486. * @param mesh defines the source mesh
  39487. * @param id defines the unique ID of the new geometry object
  39488. * @returns the new geometry object
  39489. */
  39490. Geometry.ExtractFromMesh = function (mesh, id) {
  39491. var geometry = mesh._geometry;
  39492. if (!geometry) {
  39493. return null;
  39494. }
  39495. return geometry.copy(id);
  39496. };
  39497. /**
  39498. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39499. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39500. * Be aware Math.random() could cause collisions, but:
  39501. * "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"
  39502. * @returns a string containing a new GUID
  39503. */
  39504. Geometry.RandomId = function () {
  39505. return BABYLON.Tools.RandomId();
  39506. };
  39507. /** @hidden */
  39508. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39509. var scene = mesh.getScene();
  39510. // Geometry
  39511. var geometryId = parsedGeometry.geometryId;
  39512. if (geometryId) {
  39513. var geometry = scene.getGeometryByID(geometryId);
  39514. if (geometry) {
  39515. geometry.applyToMesh(mesh);
  39516. }
  39517. }
  39518. else if (parsedGeometry instanceof ArrayBuffer) {
  39519. var binaryInfo = mesh._binaryInfo;
  39520. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39521. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39522. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39523. }
  39524. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39525. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39526. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39527. }
  39528. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39529. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39530. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39531. }
  39532. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39533. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39534. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39535. }
  39536. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39537. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39538. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39539. }
  39540. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39541. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39542. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39543. }
  39544. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39545. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39546. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39547. }
  39548. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39549. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39550. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39551. }
  39552. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39553. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39554. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39555. }
  39556. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39557. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39558. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39559. }
  39560. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39561. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39562. var floatIndices = [];
  39563. for (var i = 0; i < matricesIndicesData.length; i++) {
  39564. var index = matricesIndicesData[i];
  39565. floatIndices.push(index & 0x000000FF);
  39566. floatIndices.push((index & 0x0000FF00) >> 8);
  39567. floatIndices.push((index & 0x00FF0000) >> 16);
  39568. floatIndices.push(index >> 24);
  39569. }
  39570. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39571. }
  39572. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39573. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39574. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39575. }
  39576. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39577. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39578. mesh.setIndices(indicesData, null);
  39579. }
  39580. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39581. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39582. mesh.subMeshes = [];
  39583. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39584. var materialIndex = subMeshesData[(i * 5) + 0];
  39585. var verticesStart = subMeshesData[(i * 5) + 1];
  39586. var verticesCount = subMeshesData[(i * 5) + 2];
  39587. var indexStart = subMeshesData[(i * 5) + 3];
  39588. var indexCount = subMeshesData[(i * 5) + 4];
  39589. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39590. }
  39591. }
  39592. }
  39593. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39594. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39595. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39596. if (parsedGeometry.tangents) {
  39597. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39598. }
  39599. if (parsedGeometry.uvs) {
  39600. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39601. }
  39602. if (parsedGeometry.uvs2) {
  39603. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39604. }
  39605. if (parsedGeometry.uvs3) {
  39606. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39607. }
  39608. if (parsedGeometry.uvs4) {
  39609. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39610. }
  39611. if (parsedGeometry.uvs5) {
  39612. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39613. }
  39614. if (parsedGeometry.uvs6) {
  39615. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39616. }
  39617. if (parsedGeometry.colors) {
  39618. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39619. }
  39620. if (parsedGeometry.matricesIndices) {
  39621. if (!parsedGeometry.matricesIndices._isExpanded) {
  39622. var floatIndices = [];
  39623. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39624. var matricesIndex = parsedGeometry.matricesIndices[i];
  39625. floatIndices.push(matricesIndex & 0x000000FF);
  39626. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39627. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39628. floatIndices.push(matricesIndex >> 24);
  39629. }
  39630. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39631. }
  39632. else {
  39633. delete parsedGeometry.matricesIndices._isExpanded;
  39634. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39635. }
  39636. }
  39637. if (parsedGeometry.matricesIndicesExtra) {
  39638. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39639. var floatIndices = [];
  39640. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39641. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39642. floatIndices.push(matricesIndex & 0x000000FF);
  39643. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39644. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39645. floatIndices.push(matricesIndex >> 24);
  39646. }
  39647. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39648. }
  39649. else {
  39650. delete parsedGeometry.matricesIndices._isExpanded;
  39651. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39652. }
  39653. }
  39654. if (parsedGeometry.matricesWeights) {
  39655. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39656. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39657. }
  39658. if (parsedGeometry.matricesWeightsExtra) {
  39659. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39660. }
  39661. mesh.setIndices(parsedGeometry.indices, null);
  39662. }
  39663. // SubMeshes
  39664. if (parsedGeometry.subMeshes) {
  39665. mesh.subMeshes = [];
  39666. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39667. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39668. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39669. }
  39670. }
  39671. // Flat shading
  39672. if (mesh._shouldGenerateFlatShading) {
  39673. mesh.convertToFlatShadedMesh();
  39674. delete mesh._shouldGenerateFlatShading;
  39675. }
  39676. // Update
  39677. mesh.computeWorldMatrix(true);
  39678. // Octree
  39679. var sceneOctree = scene.selectionOctree;
  39680. if (sceneOctree !== undefined && sceneOctree !== null) {
  39681. sceneOctree.addMesh(mesh);
  39682. }
  39683. };
  39684. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39685. var epsilon = 1e-3;
  39686. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39687. return;
  39688. }
  39689. var noInfluenceBoneIndex = 0.0;
  39690. if (parsedGeometry.skeletonId > -1) {
  39691. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39692. if (!skeleton) {
  39693. return;
  39694. }
  39695. noInfluenceBoneIndex = skeleton.bones.length;
  39696. }
  39697. else {
  39698. return;
  39699. }
  39700. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39701. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39702. var matricesWeights = parsedGeometry.matricesWeights;
  39703. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39704. var influencers = parsedGeometry.numBoneInfluencer;
  39705. var size = matricesWeights.length;
  39706. for (var i = 0; i < size; i += 4) {
  39707. var weight = 0.0;
  39708. var firstZeroWeight = -1;
  39709. for (var j = 0; j < 4; j++) {
  39710. var w = matricesWeights[i + j];
  39711. weight += w;
  39712. if (w < epsilon && firstZeroWeight < 0) {
  39713. firstZeroWeight = j;
  39714. }
  39715. }
  39716. if (matricesWeightsExtra) {
  39717. for (var j = 0; j < 4; j++) {
  39718. var w = matricesWeightsExtra[i + j];
  39719. weight += w;
  39720. if (w < epsilon && firstZeroWeight < 0) {
  39721. firstZeroWeight = j + 4;
  39722. }
  39723. }
  39724. }
  39725. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39726. firstZeroWeight = influencers - 1;
  39727. }
  39728. if (weight > epsilon) {
  39729. var mweight = 1.0 / weight;
  39730. for (var j = 0; j < 4; j++) {
  39731. matricesWeights[i + j] *= mweight;
  39732. }
  39733. if (matricesWeightsExtra) {
  39734. for (var j = 0; j < 4; j++) {
  39735. matricesWeightsExtra[i + j] *= mweight;
  39736. }
  39737. }
  39738. }
  39739. else {
  39740. if (firstZeroWeight >= 4) {
  39741. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39742. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39743. }
  39744. else {
  39745. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39746. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39747. }
  39748. }
  39749. }
  39750. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39751. if (parsedGeometry.matricesWeightsExtra) {
  39752. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39753. }
  39754. };
  39755. /**
  39756. * Create a new geometry from persisted data (Using .babylon file format)
  39757. * @param parsedVertexData defines the persisted data
  39758. * @param scene defines the hosting scene
  39759. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39760. * @returns the new geometry object
  39761. */
  39762. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39763. if (scene.getGeometryByID(parsedVertexData.id)) {
  39764. return null; // null since geometry could be something else than a box...
  39765. }
  39766. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39767. if (BABYLON.Tags) {
  39768. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39769. }
  39770. if (parsedVertexData.delayLoadingFile) {
  39771. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39772. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39773. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39774. geometry._delayInfo = [];
  39775. if (parsedVertexData.hasUVs) {
  39776. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39777. }
  39778. if (parsedVertexData.hasUVs2) {
  39779. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39780. }
  39781. if (parsedVertexData.hasUVs3) {
  39782. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39783. }
  39784. if (parsedVertexData.hasUVs4) {
  39785. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39786. }
  39787. if (parsedVertexData.hasUVs5) {
  39788. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39789. }
  39790. if (parsedVertexData.hasUVs6) {
  39791. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39792. }
  39793. if (parsedVertexData.hasColors) {
  39794. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39795. }
  39796. if (parsedVertexData.hasMatricesIndices) {
  39797. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39798. }
  39799. if (parsedVertexData.hasMatricesWeights) {
  39800. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39801. }
  39802. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39803. }
  39804. else {
  39805. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39806. }
  39807. scene.pushGeometry(geometry, true);
  39808. return geometry;
  39809. };
  39810. return Geometry;
  39811. }());
  39812. BABYLON.Geometry = Geometry;
  39813. // Primitives
  39814. /// Abstract class
  39815. /**
  39816. * Abstract class used to provide common services for all typed geometries
  39817. * @hidden
  39818. */
  39819. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39820. __extends(_PrimitiveGeometry, _super);
  39821. /**
  39822. * Creates a new typed geometry
  39823. * @param id defines the unique ID of the geometry
  39824. * @param scene defines the hosting scene
  39825. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39826. * @param mesh defines the hosting mesh (can be null)
  39827. */
  39828. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39829. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39830. if (mesh === void 0) { mesh = null; }
  39831. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39832. _this._canBeRegenerated = _canBeRegenerated;
  39833. _this._beingRegenerated = true;
  39834. _this.regenerate();
  39835. _this._beingRegenerated = false;
  39836. return _this;
  39837. }
  39838. /**
  39839. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39840. * @returns true if the geometry can be regenerated
  39841. */
  39842. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39843. return this._canBeRegenerated;
  39844. };
  39845. /**
  39846. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39847. */
  39848. _PrimitiveGeometry.prototype.regenerate = function () {
  39849. if (!this._canBeRegenerated) {
  39850. return;
  39851. }
  39852. this._beingRegenerated = true;
  39853. this.setAllVerticesData(this._regenerateVertexData(), false);
  39854. this._beingRegenerated = false;
  39855. };
  39856. /**
  39857. * Clone the geometry
  39858. * @param id defines the unique ID of the new geometry
  39859. * @returns the new geometry
  39860. */
  39861. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39862. return _super.prototype.copy.call(this, id);
  39863. };
  39864. // overrides
  39865. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39866. if (!this._beingRegenerated) {
  39867. return;
  39868. }
  39869. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39870. };
  39871. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39872. if (!this._beingRegenerated) {
  39873. return;
  39874. }
  39875. _super.prototype.setVerticesData.call(this, kind, data, false);
  39876. };
  39877. // to override
  39878. /** @hidden */
  39879. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39880. throw new Error("Abstract method");
  39881. };
  39882. _PrimitiveGeometry.prototype.copy = function (id) {
  39883. throw new Error("Must be overriden in sub-classes.");
  39884. };
  39885. _PrimitiveGeometry.prototype.serialize = function () {
  39886. var serializationObject = _super.prototype.serialize.call(this);
  39887. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39888. return serializationObject;
  39889. };
  39890. return _PrimitiveGeometry;
  39891. }(Geometry));
  39892. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39893. /**
  39894. * Creates a ribbon geometry
  39895. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39896. */
  39897. var RibbonGeometry = /** @class */ (function (_super) {
  39898. __extends(RibbonGeometry, _super);
  39899. /**
  39900. * Creates a ribbon geometry
  39901. * @param id defines the unique ID of the geometry
  39902. * @param scene defines the hosting scene
  39903. * @param pathArray defines the array of paths to use
  39904. * @param closeArray defines if the last path and the first path must be joined
  39905. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39906. * @param offset defines the offset between points
  39907. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39908. * @param mesh defines the hosting mesh (can be null)
  39909. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39910. */
  39911. function RibbonGeometry(id, scene,
  39912. /**
  39913. * Defines the array of paths to use
  39914. */
  39915. pathArray,
  39916. /**
  39917. * Defines if the last and first points of each path in your pathArray must be joined
  39918. */
  39919. closeArray,
  39920. /**
  39921. * Defines if the last and first points of each path in your pathArray must be joined
  39922. */
  39923. closePath,
  39924. /**
  39925. * Defines the offset between points
  39926. */
  39927. offset, canBeRegenerated, mesh,
  39928. /**
  39929. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39930. */
  39931. side) {
  39932. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39933. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39934. _this.pathArray = pathArray;
  39935. _this.closeArray = closeArray;
  39936. _this.closePath = closePath;
  39937. _this.offset = offset;
  39938. _this.side = side;
  39939. return _this;
  39940. }
  39941. /** @hidden */
  39942. RibbonGeometry.prototype._regenerateVertexData = function () {
  39943. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39944. };
  39945. RibbonGeometry.prototype.copy = function (id) {
  39946. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39947. };
  39948. return RibbonGeometry;
  39949. }(_PrimitiveGeometry));
  39950. BABYLON.RibbonGeometry = RibbonGeometry;
  39951. /**
  39952. * Creates a box geometry
  39953. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39954. */
  39955. var BoxGeometry = /** @class */ (function (_super) {
  39956. __extends(BoxGeometry, _super);
  39957. /**
  39958. * Creates a box geometry
  39959. * @param id defines the unique ID of the geometry
  39960. * @param scene defines the hosting scene
  39961. * @param size defines the zise of the box (width, height and depth are the same)
  39962. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39963. * @param mesh defines the hosting mesh (can be null)
  39964. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39965. */
  39966. function BoxGeometry(id, scene,
  39967. /**
  39968. * Defines the zise of the box (width, height and depth are the same)
  39969. */
  39970. size, canBeRegenerated, mesh,
  39971. /**
  39972. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39973. */
  39974. side) {
  39975. if (mesh === void 0) { mesh = null; }
  39976. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39977. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39978. _this.size = size;
  39979. _this.side = side;
  39980. return _this;
  39981. }
  39982. BoxGeometry.prototype._regenerateVertexData = function () {
  39983. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39984. };
  39985. BoxGeometry.prototype.copy = function (id) {
  39986. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39987. };
  39988. BoxGeometry.prototype.serialize = function () {
  39989. var serializationObject = _super.prototype.serialize.call(this);
  39990. serializationObject.size = this.size;
  39991. return serializationObject;
  39992. };
  39993. BoxGeometry.Parse = function (parsedBox, scene) {
  39994. if (scene.getGeometryByID(parsedBox.id)) {
  39995. return null; // null since geometry could be something else than a box...
  39996. }
  39997. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39998. if (BABYLON.Tags) {
  39999. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40000. }
  40001. scene.pushGeometry(box, true);
  40002. return box;
  40003. };
  40004. return BoxGeometry;
  40005. }(_PrimitiveGeometry));
  40006. BABYLON.BoxGeometry = BoxGeometry;
  40007. /**
  40008. * Creates a sphere geometry
  40009. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40010. */
  40011. var SphereGeometry = /** @class */ (function (_super) {
  40012. __extends(SphereGeometry, _super);
  40013. /**
  40014. * Create a new sphere geometry
  40015. * @param id defines the unique ID of the geometry
  40016. * @param scene defines the hosting scene
  40017. * @param segments defines the number of segments to use to create the sphere
  40018. * @param diameter defines the diameter of the sphere
  40019. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40020. * @param mesh defines the hosting mesh (can be null)
  40021. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40022. */
  40023. function SphereGeometry(id, scene,
  40024. /**
  40025. * Defines the number of segments to use to create the sphere
  40026. */
  40027. segments,
  40028. /**
  40029. * Defines the diameter of the sphere
  40030. */
  40031. diameter, canBeRegenerated, mesh,
  40032. /**
  40033. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40034. */
  40035. side) {
  40036. if (mesh === void 0) { mesh = null; }
  40037. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40038. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40039. _this.segments = segments;
  40040. _this.diameter = diameter;
  40041. _this.side = side;
  40042. return _this;
  40043. }
  40044. SphereGeometry.prototype._regenerateVertexData = function () {
  40045. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40046. };
  40047. SphereGeometry.prototype.copy = function (id) {
  40048. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40049. };
  40050. SphereGeometry.prototype.serialize = function () {
  40051. var serializationObject = _super.prototype.serialize.call(this);
  40052. serializationObject.segments = this.segments;
  40053. serializationObject.diameter = this.diameter;
  40054. return serializationObject;
  40055. };
  40056. SphereGeometry.Parse = function (parsedSphere, scene) {
  40057. if (scene.getGeometryByID(parsedSphere.id)) {
  40058. return null; // null since geometry could be something else than a sphere...
  40059. }
  40060. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40061. if (BABYLON.Tags) {
  40062. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40063. }
  40064. scene.pushGeometry(sphere, true);
  40065. return sphere;
  40066. };
  40067. return SphereGeometry;
  40068. }(_PrimitiveGeometry));
  40069. BABYLON.SphereGeometry = SphereGeometry;
  40070. /**
  40071. * Creates a disc geometry
  40072. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40073. */
  40074. var DiscGeometry = /** @class */ (function (_super) {
  40075. __extends(DiscGeometry, _super);
  40076. /**
  40077. * Creates a new disc geometry
  40078. * @param id defines the unique ID of the geometry
  40079. * @param scene defines the hosting scene
  40080. * @param radius defines the radius of the disc
  40081. * @param tessellation defines the tesselation factor to apply to the disc
  40082. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40083. * @param mesh defines the hosting mesh (can be null)
  40084. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40085. */
  40086. function DiscGeometry(id, scene,
  40087. /**
  40088. * Defines the radius of the disc
  40089. */
  40090. radius,
  40091. /**
  40092. * Defines the tesselation factor to apply to the disc
  40093. */
  40094. tessellation, canBeRegenerated, mesh,
  40095. /**
  40096. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40097. */
  40098. side) {
  40099. if (mesh === void 0) { mesh = null; }
  40100. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40101. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40102. _this.radius = radius;
  40103. _this.tessellation = tessellation;
  40104. _this.side = side;
  40105. return _this;
  40106. }
  40107. DiscGeometry.prototype._regenerateVertexData = function () {
  40108. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40109. };
  40110. DiscGeometry.prototype.copy = function (id) {
  40111. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40112. };
  40113. return DiscGeometry;
  40114. }(_PrimitiveGeometry));
  40115. BABYLON.DiscGeometry = DiscGeometry;
  40116. /**
  40117. * Creates a new cylinder geometry
  40118. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40119. */
  40120. var CylinderGeometry = /** @class */ (function (_super) {
  40121. __extends(CylinderGeometry, _super);
  40122. /**
  40123. * Creates a new cylinder geometry
  40124. * @param id defines the unique ID of the geometry
  40125. * @param scene defines the hosting scene
  40126. * @param height defines the height of the cylinder
  40127. * @param diameterTop defines the diameter of the cylinder's top cap
  40128. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40129. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40130. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40131. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40132. * @param mesh defines the hosting mesh (can be null)
  40133. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40134. */
  40135. function CylinderGeometry(id, scene,
  40136. /**
  40137. * Defines the height of the cylinder
  40138. */
  40139. height,
  40140. /**
  40141. * Defines the diameter of the cylinder's top cap
  40142. */
  40143. diameterTop,
  40144. /**
  40145. * Defines the diameter of the cylinder's bottom cap
  40146. */
  40147. diameterBottom,
  40148. /**
  40149. * Defines the tessellation factor to apply to the cylinder
  40150. */
  40151. tessellation,
  40152. /**
  40153. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40154. */
  40155. subdivisions, canBeRegenerated, mesh,
  40156. /**
  40157. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40158. */
  40159. side) {
  40160. if (subdivisions === void 0) { subdivisions = 1; }
  40161. if (mesh === void 0) { mesh = null; }
  40162. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40163. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40164. _this.height = height;
  40165. _this.diameterTop = diameterTop;
  40166. _this.diameterBottom = diameterBottom;
  40167. _this.tessellation = tessellation;
  40168. _this.subdivisions = subdivisions;
  40169. _this.side = side;
  40170. return _this;
  40171. }
  40172. CylinderGeometry.prototype._regenerateVertexData = function () {
  40173. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40174. };
  40175. CylinderGeometry.prototype.copy = function (id) {
  40176. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40177. };
  40178. CylinderGeometry.prototype.serialize = function () {
  40179. var serializationObject = _super.prototype.serialize.call(this);
  40180. serializationObject.height = this.height;
  40181. serializationObject.diameterTop = this.diameterTop;
  40182. serializationObject.diameterBottom = this.diameterBottom;
  40183. serializationObject.tessellation = this.tessellation;
  40184. return serializationObject;
  40185. };
  40186. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40187. if (scene.getGeometryByID(parsedCylinder.id)) {
  40188. return null; // null since geometry could be something else than a cylinder...
  40189. }
  40190. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40191. if (BABYLON.Tags) {
  40192. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40193. }
  40194. scene.pushGeometry(cylinder, true);
  40195. return cylinder;
  40196. };
  40197. return CylinderGeometry;
  40198. }(_PrimitiveGeometry));
  40199. BABYLON.CylinderGeometry = CylinderGeometry;
  40200. /**
  40201. * Creates a new torus geometry
  40202. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40203. */
  40204. var TorusGeometry = /** @class */ (function (_super) {
  40205. __extends(TorusGeometry, _super);
  40206. /**
  40207. * Creates a new torus geometry
  40208. * @param id defines the unique ID of the geometry
  40209. * @param scene defines the hosting scene
  40210. * @param diameter defines the diameter of the torus
  40211. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40212. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40213. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40214. * @param mesh defines the hosting mesh (can be null)
  40215. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40216. */
  40217. function TorusGeometry(id, scene,
  40218. /**
  40219. * Defines the diameter of the torus
  40220. */
  40221. diameter,
  40222. /**
  40223. * Defines the thickness of the torus (ie. internal diameter)
  40224. */
  40225. thickness,
  40226. /**
  40227. * Defines the tesselation factor to apply to the torus
  40228. */
  40229. tessellation, canBeRegenerated, mesh,
  40230. /**
  40231. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40232. */
  40233. side) {
  40234. if (mesh === void 0) { mesh = null; }
  40235. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40236. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40237. _this.diameter = diameter;
  40238. _this.thickness = thickness;
  40239. _this.tessellation = tessellation;
  40240. _this.side = side;
  40241. return _this;
  40242. }
  40243. TorusGeometry.prototype._regenerateVertexData = function () {
  40244. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40245. };
  40246. TorusGeometry.prototype.copy = function (id) {
  40247. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40248. };
  40249. TorusGeometry.prototype.serialize = function () {
  40250. var serializationObject = _super.prototype.serialize.call(this);
  40251. serializationObject.diameter = this.diameter;
  40252. serializationObject.thickness = this.thickness;
  40253. serializationObject.tessellation = this.tessellation;
  40254. return serializationObject;
  40255. };
  40256. TorusGeometry.Parse = function (parsedTorus, scene) {
  40257. if (scene.getGeometryByID(parsedTorus.id)) {
  40258. return null; // null since geometry could be something else than a torus...
  40259. }
  40260. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40261. if (BABYLON.Tags) {
  40262. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40263. }
  40264. scene.pushGeometry(torus, true);
  40265. return torus;
  40266. };
  40267. return TorusGeometry;
  40268. }(_PrimitiveGeometry));
  40269. BABYLON.TorusGeometry = TorusGeometry;
  40270. /**
  40271. * Creates a new ground geometry
  40272. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40273. */
  40274. var GroundGeometry = /** @class */ (function (_super) {
  40275. __extends(GroundGeometry, _super);
  40276. /**
  40277. * Creates a new ground geometry
  40278. * @param id defines the unique ID of the geometry
  40279. * @param scene defines the hosting scene
  40280. * @param width defines the width of the ground
  40281. * @param height defines the height of the ground
  40282. * @param subdivisions defines the subdivisions to apply to the ground
  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. */
  40286. function GroundGeometry(id, scene,
  40287. /**
  40288. * Defines the width of the ground
  40289. */
  40290. width,
  40291. /**
  40292. * Defines the height of the ground
  40293. */
  40294. height,
  40295. /**
  40296. * Defines the subdivisions to apply to the ground
  40297. */
  40298. subdivisions, canBeRegenerated, mesh) {
  40299. if (mesh === void 0) { mesh = null; }
  40300. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40301. _this.width = width;
  40302. _this.height = height;
  40303. _this.subdivisions = subdivisions;
  40304. return _this;
  40305. }
  40306. GroundGeometry.prototype._regenerateVertexData = function () {
  40307. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40308. };
  40309. GroundGeometry.prototype.copy = function (id) {
  40310. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40311. };
  40312. GroundGeometry.prototype.serialize = function () {
  40313. var serializationObject = _super.prototype.serialize.call(this);
  40314. serializationObject.width = this.width;
  40315. serializationObject.height = this.height;
  40316. serializationObject.subdivisions = this.subdivisions;
  40317. return serializationObject;
  40318. };
  40319. GroundGeometry.Parse = function (parsedGround, scene) {
  40320. if (scene.getGeometryByID(parsedGround.id)) {
  40321. return null; // null since geometry could be something else than a ground...
  40322. }
  40323. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40324. if (BABYLON.Tags) {
  40325. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40326. }
  40327. scene.pushGeometry(ground, true);
  40328. return ground;
  40329. };
  40330. return GroundGeometry;
  40331. }(_PrimitiveGeometry));
  40332. BABYLON.GroundGeometry = GroundGeometry;
  40333. /**
  40334. * Creates a tiled ground geometry
  40335. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40336. */
  40337. var TiledGroundGeometry = /** @class */ (function (_super) {
  40338. __extends(TiledGroundGeometry, _super);
  40339. /**
  40340. * Creates a tiled ground geometry
  40341. * @param id defines the unique ID of the geometry
  40342. * @param scene defines the hosting scene
  40343. * @param xmin defines the minimum value on X axis
  40344. * @param zmin defines the minimum value on Z axis
  40345. * @param xmax defines the maximum value on X axis
  40346. * @param zmax defines the maximum value on Z axis
  40347. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40348. * @param precision defines the precision to use when computing the tiles
  40349. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40350. * @param mesh defines the hosting mesh (can be null)
  40351. */
  40352. function TiledGroundGeometry(id, scene,
  40353. /**
  40354. * Defines the minimum value on X axis
  40355. */
  40356. xmin,
  40357. /**
  40358. * Defines the minimum value on Z axis
  40359. */
  40360. zmin,
  40361. /**
  40362. * Defines the maximum value on X axis
  40363. */
  40364. xmax,
  40365. /**
  40366. * Defines the maximum value on Z axis
  40367. */
  40368. zmax,
  40369. /**
  40370. * Defines the subdivisions to apply to the ground
  40371. */
  40372. subdivisions,
  40373. /**
  40374. * Defines the precision to use when computing the tiles
  40375. */
  40376. precision, canBeRegenerated, mesh) {
  40377. if (mesh === void 0) { mesh = null; }
  40378. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40379. _this.xmin = xmin;
  40380. _this.zmin = zmin;
  40381. _this.xmax = xmax;
  40382. _this.zmax = zmax;
  40383. _this.subdivisions = subdivisions;
  40384. _this.precision = precision;
  40385. return _this;
  40386. }
  40387. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40388. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40389. };
  40390. TiledGroundGeometry.prototype.copy = function (id) {
  40391. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40392. };
  40393. return TiledGroundGeometry;
  40394. }(_PrimitiveGeometry));
  40395. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40396. /**
  40397. * Creates a plane geometry
  40398. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40399. */
  40400. var PlaneGeometry = /** @class */ (function (_super) {
  40401. __extends(PlaneGeometry, _super);
  40402. /**
  40403. * Creates a plane geometry
  40404. * @param id defines the unique ID of the geometry
  40405. * @param scene defines the hosting scene
  40406. * @param size defines the size of the plane (width === height)
  40407. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40408. * @param mesh defines the hosting mesh (can be null)
  40409. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40410. */
  40411. function PlaneGeometry(id, scene,
  40412. /**
  40413. * Defines the size of the plane (width === height)
  40414. */
  40415. size, canBeRegenerated, mesh,
  40416. /**
  40417. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40418. */
  40419. side) {
  40420. if (mesh === void 0) { mesh = null; }
  40421. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40422. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40423. _this.size = size;
  40424. _this.side = side;
  40425. return _this;
  40426. }
  40427. PlaneGeometry.prototype._regenerateVertexData = function () {
  40428. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40429. };
  40430. PlaneGeometry.prototype.copy = function (id) {
  40431. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40432. };
  40433. PlaneGeometry.prototype.serialize = function () {
  40434. var serializationObject = _super.prototype.serialize.call(this);
  40435. serializationObject.size = this.size;
  40436. return serializationObject;
  40437. };
  40438. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40439. if (scene.getGeometryByID(parsedPlane.id)) {
  40440. return null; // null since geometry could be something else than a ground...
  40441. }
  40442. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40443. if (BABYLON.Tags) {
  40444. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40445. }
  40446. scene.pushGeometry(plane, true);
  40447. return plane;
  40448. };
  40449. return PlaneGeometry;
  40450. }(_PrimitiveGeometry));
  40451. BABYLON.PlaneGeometry = PlaneGeometry;
  40452. /**
  40453. * Creates a torus knot geometry
  40454. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40455. */
  40456. var TorusKnotGeometry = /** @class */ (function (_super) {
  40457. __extends(TorusKnotGeometry, _super);
  40458. /**
  40459. * Creates a torus knot geometry
  40460. * @param id defines the unique ID of the geometry
  40461. * @param scene defines the hosting scene
  40462. * @param radius defines the radius of the torus knot
  40463. * @param tube defines the thickness of the torus knot tube
  40464. * @param radialSegments defines the number of radial segments
  40465. * @param tubularSegments defines the number of tubular segments
  40466. * @param p defines the first number of windings
  40467. * @param q defines the second number of windings
  40468. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40469. * @param mesh defines the hosting mesh (can be null)
  40470. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40471. */
  40472. function TorusKnotGeometry(id, scene,
  40473. /**
  40474. * Defines the radius of the torus knot
  40475. */
  40476. radius,
  40477. /**
  40478. * Defines the thickness of the torus knot tube
  40479. */
  40480. tube,
  40481. /**
  40482. * Defines the number of radial segments
  40483. */
  40484. radialSegments,
  40485. /**
  40486. * Defines the number of tubular segments
  40487. */
  40488. tubularSegments,
  40489. /**
  40490. * Defines the first number of windings
  40491. */
  40492. p,
  40493. /**
  40494. * Defines the second number of windings
  40495. */
  40496. q, canBeRegenerated, mesh,
  40497. /**
  40498. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40499. */
  40500. side) {
  40501. if (mesh === void 0) { mesh = null; }
  40502. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40503. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40504. _this.radius = radius;
  40505. _this.tube = tube;
  40506. _this.radialSegments = radialSegments;
  40507. _this.tubularSegments = tubularSegments;
  40508. _this.p = p;
  40509. _this.q = q;
  40510. _this.side = side;
  40511. return _this;
  40512. }
  40513. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40514. 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 });
  40515. };
  40516. TorusKnotGeometry.prototype.copy = function (id) {
  40517. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40518. };
  40519. TorusKnotGeometry.prototype.serialize = function () {
  40520. var serializationObject = _super.prototype.serialize.call(this);
  40521. serializationObject.radius = this.radius;
  40522. serializationObject.tube = this.tube;
  40523. serializationObject.radialSegments = this.radialSegments;
  40524. serializationObject.tubularSegments = this.tubularSegments;
  40525. serializationObject.p = this.p;
  40526. serializationObject.q = this.q;
  40527. return serializationObject;
  40528. };
  40529. ;
  40530. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40531. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40532. return null; // null since geometry could be something else than a ground...
  40533. }
  40534. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40535. if (BABYLON.Tags) {
  40536. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40537. }
  40538. scene.pushGeometry(torusKnot, true);
  40539. return torusKnot;
  40540. };
  40541. return TorusKnotGeometry;
  40542. }(_PrimitiveGeometry));
  40543. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40544. //}
  40545. })(BABYLON || (BABYLON = {}));
  40546. //# sourceMappingURL=babylon.geometry.js.map
  40547. var BABYLON;
  40548. (function (BABYLON) {
  40549. /**
  40550. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40551. */
  40552. var PerformanceMonitor = /** @class */ (function () {
  40553. /**
  40554. * constructor
  40555. * @param frameSampleSize The number of samples required to saturate the sliding window
  40556. */
  40557. function PerformanceMonitor(frameSampleSize) {
  40558. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40559. this._enabled = true;
  40560. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40561. }
  40562. /**
  40563. * Samples current frame
  40564. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40565. */
  40566. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40567. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40568. if (!this._enabled)
  40569. return;
  40570. if (this._lastFrameTimeMs != null) {
  40571. var dt = timeMs - this._lastFrameTimeMs;
  40572. this._rollingFrameTime.add(dt);
  40573. }
  40574. this._lastFrameTimeMs = timeMs;
  40575. };
  40576. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40577. /**
  40578. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40579. * @return Average frame time in milliseconds
  40580. */
  40581. get: function () {
  40582. return this._rollingFrameTime.average;
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40588. /**
  40589. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40590. * @return Frame time variance in milliseconds squared
  40591. */
  40592. get: function () {
  40593. return this._rollingFrameTime.variance;
  40594. },
  40595. enumerable: true,
  40596. configurable: true
  40597. });
  40598. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40599. /**
  40600. * Returns the frame time of the most recent frame
  40601. * @return Frame time in milliseconds
  40602. */
  40603. get: function () {
  40604. return this._rollingFrameTime.history(0);
  40605. },
  40606. enumerable: true,
  40607. configurable: true
  40608. });
  40609. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40610. /**
  40611. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40612. * @return Framerate in frames per second
  40613. */
  40614. get: function () {
  40615. return 1000.0 / this._rollingFrameTime.average;
  40616. },
  40617. enumerable: true,
  40618. configurable: true
  40619. });
  40620. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40621. /**
  40622. * Returns the average framerate in frames per second using the most recent frame time
  40623. * @return Framerate in frames per second
  40624. */
  40625. get: function () {
  40626. var history = this._rollingFrameTime.history(0);
  40627. if (history === 0) {
  40628. return 0;
  40629. }
  40630. return 1000.0 / history;
  40631. },
  40632. enumerable: true,
  40633. configurable: true
  40634. });
  40635. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40636. /**
  40637. * Returns true if enough samples have been taken to completely fill the sliding window
  40638. * @return true if saturated
  40639. */
  40640. get: function () {
  40641. return this._rollingFrameTime.isSaturated();
  40642. },
  40643. enumerable: true,
  40644. configurable: true
  40645. });
  40646. /**
  40647. * Enables contributions to the sliding window sample set
  40648. */
  40649. PerformanceMonitor.prototype.enable = function () {
  40650. this._enabled = true;
  40651. };
  40652. /**
  40653. * Disables contributions to the sliding window sample set
  40654. * Samples will not be interpolated over the disabled period
  40655. */
  40656. PerformanceMonitor.prototype.disable = function () {
  40657. this._enabled = false;
  40658. //clear last sample to avoid interpolating over the disabled period when next enabled
  40659. this._lastFrameTimeMs = null;
  40660. };
  40661. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40662. /**
  40663. * Returns true if sampling is enabled
  40664. * @return true if enabled
  40665. */
  40666. get: function () {
  40667. return this._enabled;
  40668. },
  40669. enumerable: true,
  40670. configurable: true
  40671. });
  40672. /**
  40673. * Resets performance monitor
  40674. */
  40675. PerformanceMonitor.prototype.reset = function () {
  40676. //clear last sample to avoid interpolating over the disabled period when next enabled
  40677. this._lastFrameTimeMs = null;
  40678. //wipe record
  40679. this._rollingFrameTime.reset();
  40680. };
  40681. return PerformanceMonitor;
  40682. }());
  40683. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40684. /**
  40685. * RollingAverage
  40686. *
  40687. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40688. */
  40689. var RollingAverage = /** @class */ (function () {
  40690. /**
  40691. * constructor
  40692. * @param length The number of samples required to saturate the sliding window
  40693. */
  40694. function RollingAverage(length) {
  40695. this._samples = new Array(length);
  40696. this.reset();
  40697. }
  40698. /**
  40699. * Adds a sample to the sample set
  40700. * @param v The sample value
  40701. */
  40702. RollingAverage.prototype.add = function (v) {
  40703. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40704. var delta;
  40705. //we need to check if we've already wrapped round
  40706. if (this.isSaturated()) {
  40707. //remove bottom of stack from mean
  40708. var bottomValue = this._samples[this._pos];
  40709. delta = bottomValue - this.average;
  40710. this.average -= delta / (this._sampleCount - 1);
  40711. this._m2 -= delta * (bottomValue - this.average);
  40712. }
  40713. else {
  40714. this._sampleCount++;
  40715. }
  40716. //add new value to mean
  40717. delta = v - this.average;
  40718. this.average += delta / (this._sampleCount);
  40719. this._m2 += delta * (v - this.average);
  40720. //set the new variance
  40721. this.variance = this._m2 / (this._sampleCount - 1);
  40722. this._samples[this._pos] = v;
  40723. this._pos++;
  40724. this._pos %= this._samples.length; //positive wrap around
  40725. };
  40726. /**
  40727. * Returns previously added values or null if outside of history or outside the sliding window domain
  40728. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40729. * @return Value previously recorded with add() or null if outside of range
  40730. */
  40731. RollingAverage.prototype.history = function (i) {
  40732. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40733. return 0;
  40734. }
  40735. var i0 = this._wrapPosition(this._pos - 1.0);
  40736. return this._samples[this._wrapPosition(i0 - i)];
  40737. };
  40738. /**
  40739. * Returns true if enough samples have been taken to completely fill the sliding window
  40740. * @return true if sample-set saturated
  40741. */
  40742. RollingAverage.prototype.isSaturated = function () {
  40743. return this._sampleCount >= this._samples.length;
  40744. };
  40745. /**
  40746. * Resets the rolling average (equivalent to 0 samples taken so far)
  40747. */
  40748. RollingAverage.prototype.reset = function () {
  40749. this.average = 0;
  40750. this.variance = 0;
  40751. this._sampleCount = 0;
  40752. this._pos = 0;
  40753. this._m2 = 0;
  40754. };
  40755. /**
  40756. * Wraps a value around the sample range boundaries
  40757. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40758. * @return Wrapped position in sample range
  40759. */
  40760. RollingAverage.prototype._wrapPosition = function (i) {
  40761. var max = this._samples.length;
  40762. return ((i % max) + max) % max;
  40763. };
  40764. return RollingAverage;
  40765. }());
  40766. BABYLON.RollingAverage = RollingAverage;
  40767. })(BABYLON || (BABYLON = {}));
  40768. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40769. var BABYLON;
  40770. (function (BABYLON) {
  40771. /**
  40772. * "Static Class" containing the most commonly used helper while dealing with material for
  40773. * rendering purpose.
  40774. *
  40775. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40776. *
  40777. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40778. */
  40779. var MaterialHelper = /** @class */ (function () {
  40780. function MaterialHelper() {
  40781. }
  40782. /**
  40783. * Bind the current view position to an effect.
  40784. * @param effect The effect to be bound
  40785. * @param scene The scene the eyes position is used from
  40786. */
  40787. MaterialHelper.BindEyePosition = function (effect, scene) {
  40788. if (scene._forcedViewPosition) {
  40789. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40790. return;
  40791. }
  40792. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40793. };
  40794. /**
  40795. * Helps preparing the defines values about the UVs in used in the effect.
  40796. * UVs are shared as much as we can accross chanels in the shaders.
  40797. * @param texture The texture we are preparing the UVs for
  40798. * @param defines The defines to update
  40799. * @param key The chanel key "diffuse", "specular"... used in the shader
  40800. */
  40801. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40802. defines._needUVs = true;
  40803. defines[key] = true;
  40804. if (texture.getTextureMatrix().isIdentity(true)) {
  40805. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40806. if (texture.coordinatesIndex === 0) {
  40807. defines["MAINUV1"] = true;
  40808. }
  40809. else {
  40810. defines["MAINUV2"] = true;
  40811. }
  40812. }
  40813. else {
  40814. defines[key + "DIRECTUV"] = 0;
  40815. }
  40816. };
  40817. /**
  40818. * Binds a texture matrix value to its corrsponding uniform
  40819. * @param texture The texture to bind the matrix for
  40820. * @param uniformBuffer The uniform buffer receivin the data
  40821. * @param key The chanel key "diffuse", "specular"... used in the shader
  40822. */
  40823. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40824. var matrix = texture.getTextureMatrix();
  40825. if (!matrix.isIdentity(true)) {
  40826. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40827. }
  40828. };
  40829. /**
  40830. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40831. * @param mesh defines the current mesh
  40832. * @param scene defines the current scene
  40833. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40834. * @param pointsCloud defines if point cloud rendering has to be turned on
  40835. * @param fogEnabled defines if fog has to be turned on
  40836. * @param alphaTest defines if alpha testing has to be turned on
  40837. * @param defines defines the current list of defines
  40838. */
  40839. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40840. if (defines._areMiscDirty) {
  40841. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40842. defines["POINTSIZE"] = pointsCloud;
  40843. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40844. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40845. defines["ALPHATEST"] = alphaTest;
  40846. }
  40847. };
  40848. /**
  40849. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40850. * @param scene defines the current scene
  40851. * @param engine defines the current engine
  40852. * @param defines specifies the list of active defines
  40853. * @param useInstances defines if instances have to be turned on
  40854. * @param useClipPlane defines if clip plane have to be turned on
  40855. */
  40856. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40857. if (useClipPlane === void 0) { useClipPlane = null; }
  40858. var changed = false;
  40859. if (useClipPlane == null) {
  40860. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40861. }
  40862. if (defines["CLIPPLANE"] !== useClipPlane) {
  40863. defines["CLIPPLANE"] = useClipPlane;
  40864. changed = true;
  40865. }
  40866. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40867. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40868. changed = true;
  40869. }
  40870. if (defines["INSTANCES"] !== useInstances) {
  40871. defines["INSTANCES"] = useInstances;
  40872. changed = true;
  40873. }
  40874. if (changed) {
  40875. defines.markAsUnprocessed();
  40876. }
  40877. };
  40878. /**
  40879. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40880. * @param mesh The mesh containing the geometry data we will draw
  40881. * @param defines The defines to update
  40882. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40883. * @param useBones Precise whether bones should be used or not (override mesh info)
  40884. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40885. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40886. * @returns false if defines are considered not dirty and have not been checked
  40887. */
  40888. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40889. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40890. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40891. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40892. return false;
  40893. }
  40894. defines._normals = defines._needNormals;
  40895. defines._uvs = defines._needUVs;
  40896. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40897. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40898. defines["TANGENT"] = true;
  40899. }
  40900. if (defines._needUVs) {
  40901. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40902. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40903. }
  40904. else {
  40905. defines["UV1"] = false;
  40906. defines["UV2"] = false;
  40907. }
  40908. if (useVertexColor) {
  40909. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40910. defines["VERTEXCOLOR"] = hasVertexColors;
  40911. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40912. }
  40913. if (useBones) {
  40914. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40915. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40916. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40917. }
  40918. else {
  40919. defines["NUM_BONE_INFLUENCERS"] = 0;
  40920. defines["BonesPerMesh"] = 0;
  40921. }
  40922. }
  40923. if (useMorphTargets) {
  40924. var manager = mesh.morphTargetManager;
  40925. if (manager) {
  40926. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40927. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40928. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40929. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40930. }
  40931. else {
  40932. defines["MORPHTARGETS_TANGENT"] = false;
  40933. defines["MORPHTARGETS_NORMAL"] = false;
  40934. defines["MORPHTARGETS"] = false;
  40935. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40936. }
  40937. }
  40938. return true;
  40939. };
  40940. /**
  40941. * Prepares the defines related to the light information passed in parameter
  40942. * @param scene The scene we are intending to draw
  40943. * @param mesh The mesh the effect is compiling for
  40944. * @param defines The defines to update
  40945. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40946. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40947. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40948. * @returns true if normals will be required for the rest of the effect
  40949. */
  40950. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40951. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40952. if (disableLighting === void 0) { disableLighting = false; }
  40953. if (!defines._areLightsDirty) {
  40954. return defines._needNormals;
  40955. }
  40956. var lightIndex = 0;
  40957. var needNormals = false;
  40958. var needRebuild = false;
  40959. var lightmapMode = false;
  40960. var shadowEnabled = false;
  40961. var specularEnabled = false;
  40962. if (scene.lightsEnabled && !disableLighting) {
  40963. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40964. var light = _a[_i];
  40965. needNormals = true;
  40966. if (defines["LIGHT" + lightIndex] === undefined) {
  40967. needRebuild = true;
  40968. }
  40969. defines["LIGHT" + lightIndex] = true;
  40970. defines["SPOTLIGHT" + lightIndex] = false;
  40971. defines["HEMILIGHT" + lightIndex] = false;
  40972. defines["POINTLIGHT" + lightIndex] = false;
  40973. defines["DIRLIGHT" + lightIndex] = false;
  40974. light.prepareLightSpecificDefines(defines, lightIndex);
  40975. // FallOff.
  40976. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40977. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40978. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40979. switch (light.falloffType) {
  40980. case BABYLON.Light.FALLOFF_GLTF:
  40981. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40982. break;
  40983. case BABYLON.Light.FALLOFF_PHYSICAL:
  40984. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40985. break;
  40986. case BABYLON.Light.FALLOFF_STANDARD:
  40987. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40988. break;
  40989. }
  40990. // Specular
  40991. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40992. specularEnabled = true;
  40993. }
  40994. // Shadows
  40995. defines["SHADOW" + lightIndex] = false;
  40996. defines["SHADOWPCF" + lightIndex] = false;
  40997. defines["SHADOWPCSS" + lightIndex] = false;
  40998. defines["SHADOWPOISSON" + lightIndex] = false;
  40999. defines["SHADOWESM" + lightIndex] = false;
  41000. defines["SHADOWCUBE" + lightIndex] = false;
  41001. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41002. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41003. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41004. var shadowGenerator = light.getShadowGenerator();
  41005. if (shadowGenerator) {
  41006. var shadowMap = shadowGenerator.getShadowMap();
  41007. if (shadowMap) {
  41008. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41009. shadowEnabled = true;
  41010. shadowGenerator.prepareDefines(defines, lightIndex);
  41011. }
  41012. }
  41013. }
  41014. }
  41015. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41016. lightmapMode = true;
  41017. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41018. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41019. }
  41020. else {
  41021. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41022. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41023. }
  41024. lightIndex++;
  41025. if (lightIndex === maxSimultaneousLights)
  41026. break;
  41027. }
  41028. }
  41029. defines["SPECULARTERM"] = specularEnabled;
  41030. defines["SHADOWS"] = shadowEnabled;
  41031. // Resetting all other lights if any
  41032. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41033. if (defines["LIGHT" + index] !== undefined) {
  41034. defines["LIGHT" + index] = false;
  41035. defines["HEMILIGHT" + lightIndex] = false;
  41036. defines["POINTLIGHT" + lightIndex] = false;
  41037. defines["DIRLIGHT" + lightIndex] = false;
  41038. defines["SPOTLIGHT" + lightIndex] = false;
  41039. defines["SHADOW" + lightIndex] = false;
  41040. }
  41041. }
  41042. var caps = scene.getEngine().getCaps();
  41043. if (defines["SHADOWFLOAT"] === undefined) {
  41044. needRebuild = true;
  41045. }
  41046. defines["SHADOWFLOAT"] = shadowEnabled &&
  41047. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41048. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41049. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41050. if (needRebuild) {
  41051. defines.rebuild();
  41052. }
  41053. return needNormals;
  41054. };
  41055. /**
  41056. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41057. * that won t be acctive due to defines being turned off.
  41058. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41059. * @param samplersList The samplers list
  41060. * @param defines The defines helping in the list generation
  41061. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41062. */
  41063. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41064. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41065. var uniformsList;
  41066. var uniformBuffersList = null;
  41067. if (uniformsListOrOptions.uniformsNames) {
  41068. var options = uniformsListOrOptions;
  41069. uniformsList = options.uniformsNames;
  41070. uniformBuffersList = options.uniformBuffersNames;
  41071. samplersList = options.samplers;
  41072. defines = options.defines;
  41073. maxSimultaneousLights = options.maxSimultaneousLights;
  41074. }
  41075. else {
  41076. uniformsList = uniformsListOrOptions;
  41077. if (!samplersList) {
  41078. samplersList = [];
  41079. }
  41080. }
  41081. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41082. if (!defines["LIGHT" + lightIndex]) {
  41083. break;
  41084. }
  41085. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41086. if (uniformBuffersList) {
  41087. uniformBuffersList.push("Light" + lightIndex);
  41088. }
  41089. samplersList.push("shadowSampler" + lightIndex);
  41090. samplersList.push("depthSampler" + lightIndex);
  41091. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41092. samplersList.push("projectionLightSampler" + lightIndex);
  41093. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41094. }
  41095. }
  41096. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41097. uniformsList.push("morphTargetInfluences");
  41098. }
  41099. };
  41100. /**
  41101. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41102. * @param defines The defines to update while falling back
  41103. * @param fallbacks The authorized effect fallbacks
  41104. * @param maxSimultaneousLights The maximum number of lights allowed
  41105. * @param rank the current rank of the Effect
  41106. * @returns The newly affected rank
  41107. */
  41108. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41109. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41110. if (rank === void 0) { rank = 0; }
  41111. var lightFallbackRank = 0;
  41112. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41113. if (!defines["LIGHT" + lightIndex]) {
  41114. break;
  41115. }
  41116. if (lightIndex > 0) {
  41117. lightFallbackRank = rank + lightIndex;
  41118. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41119. }
  41120. if (!defines["SHADOWS"]) {
  41121. if (defines["SHADOW" + lightIndex]) {
  41122. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41123. }
  41124. if (defines["SHADOWPCF" + lightIndex]) {
  41125. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41126. }
  41127. if (defines["SHADOWPCSS" + lightIndex]) {
  41128. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41129. }
  41130. if (defines["SHADOWPOISSON" + lightIndex]) {
  41131. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41132. }
  41133. if (defines["SHADOWESM" + lightIndex]) {
  41134. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41135. }
  41136. }
  41137. }
  41138. return lightFallbackRank++;
  41139. };
  41140. /**
  41141. * Prepares the list of attributes required for morph targets according to the effect defines.
  41142. * @param attribs The current list of supported attribs
  41143. * @param mesh The mesh to prepare the morph targets attributes for
  41144. * @param defines The current Defines of the effect
  41145. */
  41146. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41147. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41148. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41149. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41150. var manager = mesh.morphTargetManager;
  41151. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41152. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41153. for (var index = 0; index < influencers; index++) {
  41154. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41155. if (normal) {
  41156. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41157. }
  41158. if (tangent) {
  41159. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41160. }
  41161. if (attribs.length > maxAttributesCount) {
  41162. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41163. }
  41164. }
  41165. }
  41166. };
  41167. /**
  41168. * Prepares the list of attributes required for bones according to the effect defines.
  41169. * @param attribs The current list of supported attribs
  41170. * @param mesh The mesh to prepare the bones attributes for
  41171. * @param defines The current Defines of the effect
  41172. * @param fallbacks The current efffect fallback strategy
  41173. */
  41174. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41175. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41176. fallbacks.addCPUSkinningFallback(0, mesh);
  41177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41179. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41180. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41181. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41182. }
  41183. }
  41184. };
  41185. /**
  41186. * Prepares the list of attributes required for instances according to the effect defines.
  41187. * @param attribs The current list of supported attribs
  41188. * @param defines The current Defines of the effect
  41189. */
  41190. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41191. if (defines["INSTANCES"]) {
  41192. attribs.push("world0");
  41193. attribs.push("world1");
  41194. attribs.push("world2");
  41195. attribs.push("world3");
  41196. }
  41197. };
  41198. /**
  41199. * Binds the light shadow information to the effect for the given mesh.
  41200. * @param light The light containing the generator
  41201. * @param scene The scene the lights belongs to
  41202. * @param mesh The mesh we are binding the information to render
  41203. * @param lightIndex The light index in the effect used to render the mesh
  41204. * @param effect The effect we are binding the data to
  41205. */
  41206. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41207. if (light.shadowEnabled && mesh.receiveShadows) {
  41208. var shadowGenerator = light.getShadowGenerator();
  41209. if (shadowGenerator) {
  41210. shadowGenerator.bindShadowLight(lightIndex, effect);
  41211. }
  41212. }
  41213. };
  41214. /**
  41215. * Binds the light information to the effect.
  41216. * @param light The light containing the generator
  41217. * @param effect The effect we are binding the data to
  41218. * @param lightIndex The light index in the effect used to render
  41219. */
  41220. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41221. light.transferToEffect(effect, lightIndex + "");
  41222. };
  41223. /**
  41224. * Binds the lights information from the scene to the effect for the given mesh.
  41225. * @param scene The scene the lights belongs to
  41226. * @param mesh The mesh we are binding the information to render
  41227. * @param effect The effect we are binding the data to
  41228. * @param defines The generated defines for the effect
  41229. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41230. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41231. */
  41232. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41233. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41234. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41235. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41236. for (var i = 0; i < len; i++) {
  41237. var light = mesh._lightSources[i];
  41238. var iAsString = i.toString();
  41239. var scaledIntensity = light.getScaledIntensity();
  41240. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41241. MaterialHelper.BindLightProperties(light, effect, i);
  41242. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41243. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41244. if (defines["SPECULARTERM"]) {
  41245. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41246. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41247. }
  41248. // Shadows
  41249. if (scene.shadowsEnabled) {
  41250. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41251. }
  41252. light._uniformBuffer.update();
  41253. }
  41254. };
  41255. /**
  41256. * Binds the fog information from the scene to the effect for the given mesh.
  41257. * @param scene The scene the lights belongs to
  41258. * @param mesh The mesh we are binding the information to render
  41259. * @param effect The effect we are binding the data to
  41260. */
  41261. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41262. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41263. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41264. effect.setColor3("vFogColor", scene.fogColor);
  41265. }
  41266. };
  41267. /**
  41268. * Binds the bones information from the mesh to the effect.
  41269. * @param mesh The mesh we are binding the information to render
  41270. * @param effect The effect we are binding the data to
  41271. */
  41272. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41273. if (!effect || !mesh) {
  41274. return;
  41275. }
  41276. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41277. mesh.computeBonesUsingShaders = false;
  41278. }
  41279. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41280. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41281. if (matrices) {
  41282. effect.setMatrices("mBones", matrices);
  41283. }
  41284. }
  41285. };
  41286. /**
  41287. * Binds the morph targets information from the mesh to the effect.
  41288. * @param abstractMesh The mesh we are binding the information to render
  41289. * @param effect The effect we are binding the data to
  41290. */
  41291. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41292. var manager = abstractMesh.morphTargetManager;
  41293. if (!abstractMesh || !manager) {
  41294. return;
  41295. }
  41296. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41297. };
  41298. /**
  41299. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41300. * @param defines The generated defines used in the effect
  41301. * @param effect The effect we are binding the data to
  41302. * @param scene The scene we are willing to render with logarithmic scale for
  41303. */
  41304. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41305. if (defines["LOGARITHMICDEPTH"]) {
  41306. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41307. }
  41308. };
  41309. /**
  41310. * Binds the clip plane information from the scene to the effect.
  41311. * @param scene The scene the clip plane information are extracted from
  41312. * @param effect The effect we are binding the data to
  41313. */
  41314. MaterialHelper.BindClipPlane = function (effect, scene) {
  41315. if (scene.clipPlane) {
  41316. var clipPlane = scene.clipPlane;
  41317. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41318. }
  41319. };
  41320. return MaterialHelper;
  41321. }());
  41322. BABYLON.MaterialHelper = MaterialHelper;
  41323. })(BABYLON || (BABYLON = {}));
  41324. //# sourceMappingURL=babylon.materialHelper.js.map
  41325. var BABYLON;
  41326. (function (BABYLON) {
  41327. var PushMaterial = /** @class */ (function (_super) {
  41328. __extends(PushMaterial, _super);
  41329. function PushMaterial(name, scene) {
  41330. var _this = _super.call(this, name, scene) || this;
  41331. _this._normalMatrix = new BABYLON.Matrix();
  41332. _this.storeEffectOnSubMeshes = true;
  41333. return _this;
  41334. }
  41335. PushMaterial.prototype.getEffect = function () {
  41336. return this._activeEffect;
  41337. };
  41338. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41339. if (!mesh) {
  41340. return false;
  41341. }
  41342. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41343. return true;
  41344. }
  41345. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41346. };
  41347. /**
  41348. * Binds the given world matrix to the active effect
  41349. *
  41350. * @param world the matrix to bind
  41351. */
  41352. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41353. this._activeEffect.setMatrix("world", world);
  41354. };
  41355. /**
  41356. * Binds the given normal matrix to the active effect
  41357. *
  41358. * @param normalMatrix the matrix to bind
  41359. */
  41360. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41361. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41362. };
  41363. PushMaterial.prototype.bind = function (world, mesh) {
  41364. if (!mesh) {
  41365. return;
  41366. }
  41367. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41368. };
  41369. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41370. if (effect === void 0) { effect = null; }
  41371. _super.prototype._afterBind.call(this, mesh);
  41372. this.getScene()._cachedEffect = effect;
  41373. };
  41374. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41375. if (visibility === void 0) { visibility = 1; }
  41376. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41377. };
  41378. return PushMaterial;
  41379. }(BABYLON.Material));
  41380. BABYLON.PushMaterial = PushMaterial;
  41381. })(BABYLON || (BABYLON = {}));
  41382. //# sourceMappingURL=babylon.pushMaterial.js.map
  41383. var BABYLON;
  41384. (function (BABYLON) {
  41385. /** @hidden */
  41386. var StandardMaterialDefines = /** @class */ (function (_super) {
  41387. __extends(StandardMaterialDefines, _super);
  41388. function StandardMaterialDefines() {
  41389. var _this = _super.call(this) || this;
  41390. _this.MAINUV1 = false;
  41391. _this.MAINUV2 = false;
  41392. _this.DIFFUSE = false;
  41393. _this.DIFFUSEDIRECTUV = 0;
  41394. _this.AMBIENT = false;
  41395. _this.AMBIENTDIRECTUV = 0;
  41396. _this.OPACITY = false;
  41397. _this.OPACITYDIRECTUV = 0;
  41398. _this.OPACITYRGB = false;
  41399. _this.REFLECTION = false;
  41400. _this.EMISSIVE = false;
  41401. _this.EMISSIVEDIRECTUV = 0;
  41402. _this.SPECULAR = false;
  41403. _this.SPECULARDIRECTUV = 0;
  41404. _this.BUMP = false;
  41405. _this.BUMPDIRECTUV = 0;
  41406. _this.PARALLAX = false;
  41407. _this.PARALLAXOCCLUSION = false;
  41408. _this.SPECULAROVERALPHA = false;
  41409. _this.CLIPPLANE = false;
  41410. _this.ALPHATEST = false;
  41411. _this.DEPTHPREPASS = false;
  41412. _this.ALPHAFROMDIFFUSE = false;
  41413. _this.POINTSIZE = false;
  41414. _this.FOG = false;
  41415. _this.SPECULARTERM = false;
  41416. _this.DIFFUSEFRESNEL = false;
  41417. _this.OPACITYFRESNEL = false;
  41418. _this.REFLECTIONFRESNEL = false;
  41419. _this.REFRACTIONFRESNEL = false;
  41420. _this.EMISSIVEFRESNEL = false;
  41421. _this.FRESNEL = false;
  41422. _this.NORMAL = false;
  41423. _this.UV1 = false;
  41424. _this.UV2 = false;
  41425. _this.VERTEXCOLOR = false;
  41426. _this.VERTEXALPHA = false;
  41427. _this.NUM_BONE_INFLUENCERS = 0;
  41428. _this.BonesPerMesh = 0;
  41429. _this.INSTANCES = false;
  41430. _this.GLOSSINESS = false;
  41431. _this.ROUGHNESS = false;
  41432. _this.EMISSIVEASILLUMINATION = false;
  41433. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41434. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41435. _this.LIGHTMAP = false;
  41436. _this.LIGHTMAPDIRECTUV = 0;
  41437. _this.OBJECTSPACE_NORMALMAP = false;
  41438. _this.USELIGHTMAPASSHADOWMAP = false;
  41439. _this.REFLECTIONMAP_3D = false;
  41440. _this.REFLECTIONMAP_SPHERICAL = false;
  41441. _this.REFLECTIONMAP_PLANAR = false;
  41442. _this.REFLECTIONMAP_CUBIC = false;
  41443. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41444. _this.REFLECTIONMAP_PROJECTION = false;
  41445. _this.REFLECTIONMAP_SKYBOX = false;
  41446. _this.REFLECTIONMAP_EXPLICIT = false;
  41447. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41448. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41449. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41450. _this.INVERTCUBICMAP = false;
  41451. _this.LOGARITHMICDEPTH = false;
  41452. _this.REFRACTION = false;
  41453. _this.REFRACTIONMAP_3D = false;
  41454. _this.REFLECTIONOVERALPHA = false;
  41455. _this.TWOSIDEDLIGHTING = false;
  41456. _this.SHADOWFLOAT = false;
  41457. _this.MORPHTARGETS = false;
  41458. _this.MORPHTARGETS_NORMAL = false;
  41459. _this.MORPHTARGETS_TANGENT = false;
  41460. _this.NUM_MORPH_INFLUENCERS = 0;
  41461. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41462. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41463. _this.IMAGEPROCESSING = false;
  41464. _this.VIGNETTE = false;
  41465. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41466. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41467. _this.TONEMAPPING = false;
  41468. _this.CONTRAST = false;
  41469. _this.COLORCURVES = false;
  41470. _this.COLORGRADING = false;
  41471. _this.COLORGRADING3D = false;
  41472. _this.SAMPLER3DGREENDEPTH = false;
  41473. _this.SAMPLER3DBGRMAP = false;
  41474. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41475. /**
  41476. * If the reflection texture on this material is in linear color space
  41477. * @hidden
  41478. */
  41479. _this.IS_REFLECTION_LINEAR = false;
  41480. /**
  41481. * If the refraction texture on this material is in linear color space
  41482. * @hidden
  41483. */
  41484. _this.IS_REFRACTION_LINEAR = false;
  41485. _this.EXPOSURE = false;
  41486. _this.rebuild();
  41487. return _this;
  41488. }
  41489. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41490. var modes = [
  41491. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41492. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41493. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41494. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41495. ];
  41496. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41497. var mode = modes_1[_i];
  41498. this[mode] = (mode === modeToEnable);
  41499. }
  41500. };
  41501. return StandardMaterialDefines;
  41502. }(BABYLON.MaterialDefines));
  41503. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41504. var StandardMaterial = /** @class */ (function (_super) {
  41505. __extends(StandardMaterial, _super);
  41506. function StandardMaterial(name, scene) {
  41507. var _this = _super.call(this, name, scene) || this;
  41508. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41509. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41510. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41511. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41512. _this.specularPower = 64;
  41513. _this._useAlphaFromDiffuseTexture = false;
  41514. _this._useEmissiveAsIllumination = false;
  41515. _this._linkEmissiveWithDiffuse = false;
  41516. _this._useSpecularOverAlpha = false;
  41517. _this._useReflectionOverAlpha = false;
  41518. _this._disableLighting = false;
  41519. _this._useObjectSpaceNormalMap = false;
  41520. _this._useParallax = false;
  41521. _this._useParallaxOcclusion = false;
  41522. _this.parallaxScaleBias = 0.05;
  41523. _this._roughness = 0;
  41524. _this.indexOfRefraction = 0.98;
  41525. _this.invertRefractionY = true;
  41526. /**
  41527. * Defines the alpha limits in alpha test mode
  41528. */
  41529. _this.alphaCutOff = 0.4;
  41530. _this._useLightmapAsShadowmap = false;
  41531. _this._useReflectionFresnelFromSpecular = false;
  41532. _this._useGlossinessFromSpecularMapAlpha = false;
  41533. _this._maxSimultaneousLights = 4;
  41534. /**
  41535. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41536. */
  41537. _this._invertNormalMapX = false;
  41538. /**
  41539. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41540. */
  41541. _this._invertNormalMapY = false;
  41542. /**
  41543. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41544. */
  41545. _this._twoSidedLighting = false;
  41546. _this._renderTargets = new BABYLON.SmartArray(16);
  41547. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41548. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41549. // Setup the default processing configuration to the scene.
  41550. _this._attachImageProcessingConfiguration(null);
  41551. _this.getRenderTargetTextures = function () {
  41552. _this._renderTargets.reset();
  41553. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41554. _this._renderTargets.push(_this._reflectionTexture);
  41555. }
  41556. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41557. _this._renderTargets.push(_this._refractionTexture);
  41558. }
  41559. return _this._renderTargets;
  41560. };
  41561. return _this;
  41562. }
  41563. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41564. /**
  41565. * Gets the image processing configuration used either in this material.
  41566. */
  41567. get: function () {
  41568. return this._imageProcessingConfiguration;
  41569. },
  41570. /**
  41571. * Sets the Default image processing configuration used either in the this material.
  41572. *
  41573. * If sets to null, the scene one is in use.
  41574. */
  41575. set: function (value) {
  41576. this._attachImageProcessingConfiguration(value);
  41577. // Ensure the effect will be rebuilt.
  41578. this._markAllSubMeshesAsTexturesDirty();
  41579. },
  41580. enumerable: true,
  41581. configurable: true
  41582. });
  41583. /**
  41584. * Attaches a new image processing configuration to the Standard Material.
  41585. * @param configuration
  41586. */
  41587. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41588. var _this = this;
  41589. if (configuration === this._imageProcessingConfiguration) {
  41590. return;
  41591. }
  41592. // Detaches observer.
  41593. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41594. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41595. }
  41596. // Pick the scene configuration if needed.
  41597. if (!configuration) {
  41598. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41599. }
  41600. else {
  41601. this._imageProcessingConfiguration = configuration;
  41602. }
  41603. // Attaches observer.
  41604. if (this._imageProcessingConfiguration) {
  41605. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41606. _this._markAllSubMeshesAsImageProcessingDirty();
  41607. });
  41608. }
  41609. };
  41610. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41611. /**
  41612. * Gets wether the color curves effect is enabled.
  41613. */
  41614. get: function () {
  41615. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41616. },
  41617. /**
  41618. * Sets wether the color curves effect is enabled.
  41619. */
  41620. set: function (value) {
  41621. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41622. },
  41623. enumerable: true,
  41624. configurable: true
  41625. });
  41626. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41627. /**
  41628. * Gets wether the color grading effect is enabled.
  41629. */
  41630. get: function () {
  41631. return this.imageProcessingConfiguration.colorGradingEnabled;
  41632. },
  41633. /**
  41634. * Gets wether the color grading effect is enabled.
  41635. */
  41636. set: function (value) {
  41637. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41638. },
  41639. enumerable: true,
  41640. configurable: true
  41641. });
  41642. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41643. /**
  41644. * Gets wether tonemapping is enabled or not.
  41645. */
  41646. get: function () {
  41647. return this._imageProcessingConfiguration.toneMappingEnabled;
  41648. },
  41649. /**
  41650. * Sets wether tonemapping is enabled or not
  41651. */
  41652. set: function (value) {
  41653. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41654. },
  41655. enumerable: true,
  41656. configurable: true
  41657. });
  41658. ;
  41659. ;
  41660. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41661. /**
  41662. * The camera exposure used on this material.
  41663. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41664. * This corresponds to a photographic exposure.
  41665. */
  41666. get: function () {
  41667. return this._imageProcessingConfiguration.exposure;
  41668. },
  41669. /**
  41670. * The camera exposure used on this material.
  41671. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41672. * This corresponds to a photographic exposure.
  41673. */
  41674. set: function (value) {
  41675. this._imageProcessingConfiguration.exposure = value;
  41676. },
  41677. enumerable: true,
  41678. configurable: true
  41679. });
  41680. ;
  41681. ;
  41682. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41683. /**
  41684. * Gets The camera contrast used on this material.
  41685. */
  41686. get: function () {
  41687. return this._imageProcessingConfiguration.contrast;
  41688. },
  41689. /**
  41690. * Sets The camera contrast used on this material.
  41691. */
  41692. set: function (value) {
  41693. this._imageProcessingConfiguration.contrast = value;
  41694. },
  41695. enumerable: true,
  41696. configurable: true
  41697. });
  41698. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41699. /**
  41700. * Gets the Color Grading 2D Lookup Texture.
  41701. */
  41702. get: function () {
  41703. return this._imageProcessingConfiguration.colorGradingTexture;
  41704. },
  41705. /**
  41706. * Sets the Color Grading 2D Lookup Texture.
  41707. */
  41708. set: function (value) {
  41709. this._imageProcessingConfiguration.colorGradingTexture = value;
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41715. /**
  41716. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41717. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41718. * 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;
  41719. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41720. */
  41721. get: function () {
  41722. return this._imageProcessingConfiguration.colorCurves;
  41723. },
  41724. /**
  41725. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41726. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41727. * 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;
  41728. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41729. */
  41730. set: function (value) {
  41731. this._imageProcessingConfiguration.colorCurves = value;
  41732. },
  41733. enumerable: true,
  41734. configurable: true
  41735. });
  41736. StandardMaterial.prototype.getClassName = function () {
  41737. return "StandardMaterial";
  41738. };
  41739. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41740. get: function () {
  41741. return this._useLogarithmicDepth;
  41742. },
  41743. set: function (value) {
  41744. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41745. this._markAllSubMeshesAsMiscDirty();
  41746. },
  41747. enumerable: true,
  41748. configurable: true
  41749. });
  41750. StandardMaterial.prototype.needAlphaBlending = function () {
  41751. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41752. };
  41753. StandardMaterial.prototype.needAlphaTesting = function () {
  41754. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41755. };
  41756. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41757. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41758. };
  41759. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41760. return this._diffuseTexture;
  41761. };
  41762. /**
  41763. * Child classes can use it to update shaders
  41764. */
  41765. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41766. if (useInstances === void 0) { useInstances = false; }
  41767. if (subMesh.effect && this.isFrozen) {
  41768. if (this._wasPreviouslyReady) {
  41769. return true;
  41770. }
  41771. }
  41772. if (!subMesh._materialDefines) {
  41773. subMesh._materialDefines = new StandardMaterialDefines();
  41774. }
  41775. var scene = this.getScene();
  41776. var defines = subMesh._materialDefines;
  41777. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41778. if (defines._renderId === scene.getRenderId()) {
  41779. return true;
  41780. }
  41781. }
  41782. var engine = scene.getEngine();
  41783. // Lights
  41784. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41785. // Textures
  41786. if (defines._areTexturesDirty) {
  41787. defines._needUVs = false;
  41788. defines.MAINUV1 = false;
  41789. defines.MAINUV2 = false;
  41790. if (scene.texturesEnabled) {
  41791. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41792. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41793. return false;
  41794. }
  41795. else {
  41796. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41797. }
  41798. }
  41799. else {
  41800. defines.DIFFUSE = false;
  41801. }
  41802. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41803. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41804. return false;
  41805. }
  41806. else {
  41807. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41808. }
  41809. }
  41810. else {
  41811. defines.AMBIENT = false;
  41812. }
  41813. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41814. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41815. return false;
  41816. }
  41817. else {
  41818. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41819. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41820. }
  41821. }
  41822. else {
  41823. defines.OPACITY = false;
  41824. }
  41825. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41826. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41827. return false;
  41828. }
  41829. else {
  41830. defines._needNormals = true;
  41831. defines.REFLECTION = true;
  41832. defines.ROUGHNESS = (this._roughness > 0);
  41833. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41834. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41835. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41836. switch (this._reflectionTexture.coordinatesMode) {
  41837. case BABYLON.Texture.EXPLICIT_MODE:
  41838. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41839. break;
  41840. case BABYLON.Texture.PLANAR_MODE:
  41841. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41842. break;
  41843. case BABYLON.Texture.PROJECTION_MODE:
  41844. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41845. break;
  41846. case BABYLON.Texture.SKYBOX_MODE:
  41847. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41848. break;
  41849. case BABYLON.Texture.SPHERICAL_MODE:
  41850. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41851. break;
  41852. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41853. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41854. break;
  41855. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41856. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41857. break;
  41858. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41859. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41860. break;
  41861. case BABYLON.Texture.CUBIC_MODE:
  41862. case BABYLON.Texture.INVCUBIC_MODE:
  41863. default:
  41864. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41865. break;
  41866. }
  41867. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41868. }
  41869. }
  41870. else {
  41871. defines.REFLECTION = false;
  41872. }
  41873. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41874. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41875. return false;
  41876. }
  41877. else {
  41878. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41879. }
  41880. }
  41881. else {
  41882. defines.EMISSIVE = false;
  41883. }
  41884. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41885. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41886. return false;
  41887. }
  41888. else {
  41889. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41890. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41891. }
  41892. }
  41893. else {
  41894. defines.LIGHTMAP = false;
  41895. }
  41896. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41897. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41898. return false;
  41899. }
  41900. else {
  41901. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41902. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41903. }
  41904. }
  41905. else {
  41906. defines.SPECULAR = false;
  41907. }
  41908. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41909. // Bump texure can not be not blocking.
  41910. if (!this._bumpTexture.isReady()) {
  41911. return false;
  41912. }
  41913. else {
  41914. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41915. defines.PARALLAX = this._useParallax;
  41916. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41917. }
  41918. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41919. }
  41920. else {
  41921. defines.BUMP = false;
  41922. }
  41923. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41924. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41925. return false;
  41926. }
  41927. else {
  41928. defines._needUVs = true;
  41929. defines.REFRACTION = true;
  41930. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41931. }
  41932. }
  41933. else {
  41934. defines.REFRACTION = false;
  41935. }
  41936. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41937. }
  41938. else {
  41939. defines.DIFFUSE = false;
  41940. defines.AMBIENT = false;
  41941. defines.OPACITY = false;
  41942. defines.REFLECTION = false;
  41943. defines.EMISSIVE = false;
  41944. defines.LIGHTMAP = false;
  41945. defines.BUMP = false;
  41946. defines.REFRACTION = false;
  41947. }
  41948. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41949. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41950. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41951. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41952. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41953. }
  41954. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41955. if (!this._imageProcessingConfiguration.isReady()) {
  41956. return false;
  41957. }
  41958. this._imageProcessingConfiguration.prepareDefines(defines);
  41959. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41960. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41961. }
  41962. if (defines._areFresnelDirty) {
  41963. if (StandardMaterial.FresnelEnabled) {
  41964. // Fresnel
  41965. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41966. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41967. this._reflectionFresnelParameters) {
  41968. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41969. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41970. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41971. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41972. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41973. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41974. defines._needNormals = true;
  41975. defines.FRESNEL = true;
  41976. }
  41977. }
  41978. else {
  41979. defines.FRESNEL = false;
  41980. }
  41981. }
  41982. // Misc.
  41983. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41984. // Attribs
  41985. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41986. // Values that need to be evaluated on every frame
  41987. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41988. // Get correct effect
  41989. if (defines.isDirty) {
  41990. defines.markAsProcessed();
  41991. scene.resetCachedMaterial();
  41992. // Fallbacks
  41993. var fallbacks = new BABYLON.EffectFallbacks();
  41994. if (defines.REFLECTION) {
  41995. fallbacks.addFallback(0, "REFLECTION");
  41996. }
  41997. if (defines.SPECULAR) {
  41998. fallbacks.addFallback(0, "SPECULAR");
  41999. }
  42000. if (defines.BUMP) {
  42001. fallbacks.addFallback(0, "BUMP");
  42002. }
  42003. if (defines.PARALLAX) {
  42004. fallbacks.addFallback(1, "PARALLAX");
  42005. }
  42006. if (defines.PARALLAXOCCLUSION) {
  42007. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42008. }
  42009. if (defines.SPECULAROVERALPHA) {
  42010. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42011. }
  42012. if (defines.FOG) {
  42013. fallbacks.addFallback(1, "FOG");
  42014. }
  42015. if (defines.POINTSIZE) {
  42016. fallbacks.addFallback(0, "POINTSIZE");
  42017. }
  42018. if (defines.LOGARITHMICDEPTH) {
  42019. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42020. }
  42021. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42022. if (defines.SPECULARTERM) {
  42023. fallbacks.addFallback(0, "SPECULARTERM");
  42024. }
  42025. if (defines.DIFFUSEFRESNEL) {
  42026. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42027. }
  42028. if (defines.OPACITYFRESNEL) {
  42029. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42030. }
  42031. if (defines.REFLECTIONFRESNEL) {
  42032. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42033. }
  42034. if (defines.EMISSIVEFRESNEL) {
  42035. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42036. }
  42037. if (defines.FRESNEL) {
  42038. fallbacks.addFallback(4, "FRESNEL");
  42039. }
  42040. //Attributes
  42041. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42042. if (defines.NORMAL) {
  42043. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42044. }
  42045. if (defines.UV1) {
  42046. attribs.push(BABYLON.VertexBuffer.UVKind);
  42047. }
  42048. if (defines.UV2) {
  42049. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42050. }
  42051. if (defines.VERTEXCOLOR) {
  42052. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42053. }
  42054. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42055. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42056. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42057. var shaderName = "default";
  42058. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42059. "vFogInfos", "vFogColor", "pointSize",
  42060. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42061. "mBones",
  42062. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42063. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42064. "vReflectionPosition", "vReflectionSize",
  42065. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42066. ];
  42067. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42068. var uniformBuffers = ["Material", "Scene"];
  42069. if (BABYLON.ImageProcessingConfiguration) {
  42070. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42071. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42072. }
  42073. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42074. uniformsNames: uniforms,
  42075. uniformBuffersNames: uniformBuffers,
  42076. samplers: samplers,
  42077. defines: defines,
  42078. maxSimultaneousLights: this._maxSimultaneousLights
  42079. });
  42080. if (this.customShaderNameResolve) {
  42081. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42082. }
  42083. var join = defines.toString();
  42084. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42085. attributes: attribs,
  42086. uniformsNames: uniforms,
  42087. uniformBuffersNames: uniformBuffers,
  42088. samplers: samplers,
  42089. defines: join,
  42090. fallbacks: fallbacks,
  42091. onCompiled: this.onCompiled,
  42092. onError: this.onError,
  42093. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42094. }, engine), defines);
  42095. this.buildUniformLayout();
  42096. }
  42097. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42098. return false;
  42099. }
  42100. defines._renderId = scene.getRenderId();
  42101. this._wasPreviouslyReady = true;
  42102. return true;
  42103. };
  42104. StandardMaterial.prototype.buildUniformLayout = function () {
  42105. // Order is important !
  42106. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42107. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42108. this._uniformBuffer.addUniform("opacityParts", 4);
  42109. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42110. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42111. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42112. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42113. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42114. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42115. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42116. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42117. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42118. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42119. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42120. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42121. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42122. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42123. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42124. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42125. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42126. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42127. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42128. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42129. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42130. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42131. this._uniformBuffer.addUniform("specularMatrix", 16);
  42132. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42133. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42134. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42135. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42136. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42137. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42138. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42139. this._uniformBuffer.addUniform("pointSize", 1);
  42140. this._uniformBuffer.create();
  42141. };
  42142. StandardMaterial.prototype.unbind = function () {
  42143. if (this._activeEffect) {
  42144. var needFlag = false;
  42145. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42146. this._activeEffect.setTexture("reflection2DSampler", null);
  42147. needFlag = true;
  42148. }
  42149. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42150. this._activeEffect.setTexture("refraction2DSampler", null);
  42151. needFlag = true;
  42152. }
  42153. if (needFlag) {
  42154. this._markAllSubMeshesAsTexturesDirty();
  42155. }
  42156. }
  42157. _super.prototype.unbind.call(this);
  42158. };
  42159. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42160. var scene = this.getScene();
  42161. var defines = subMesh._materialDefines;
  42162. if (!defines) {
  42163. return;
  42164. }
  42165. var effect = subMesh.effect;
  42166. if (!effect) {
  42167. return;
  42168. }
  42169. this._activeEffect = effect;
  42170. // Matrices
  42171. this.bindOnlyWorldMatrix(world);
  42172. // Normal Matrix
  42173. if (defines.OBJECTSPACE_NORMALMAP) {
  42174. world.toNormalMatrix(this._normalMatrix);
  42175. this.bindOnlyNormalMatrix(this._normalMatrix);
  42176. }
  42177. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42178. // Bones
  42179. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42180. if (mustRebind) {
  42181. this._uniformBuffer.bindToEffect(effect, "Material");
  42182. this.bindViewProjection(effect);
  42183. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42184. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42185. // Fresnel
  42186. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42187. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42188. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42189. }
  42190. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42191. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42192. }
  42193. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42194. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42195. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42196. }
  42197. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42198. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42199. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42200. }
  42201. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42202. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42203. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42204. }
  42205. }
  42206. // Textures
  42207. if (scene.texturesEnabled) {
  42208. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42209. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42210. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42211. if (this._diffuseTexture.hasAlpha) {
  42212. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42213. }
  42214. }
  42215. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42216. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42217. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42218. }
  42219. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42220. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42221. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42222. }
  42223. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42224. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42225. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42226. if (this._reflectionTexture.boundingBoxSize) {
  42227. var cubeTexture = this._reflectionTexture;
  42228. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42229. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42230. }
  42231. }
  42232. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42233. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42234. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42235. }
  42236. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42237. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42238. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42239. }
  42240. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42241. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42242. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42243. }
  42244. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42245. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42246. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42247. if (scene._mirroredCameraPosition) {
  42248. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42249. }
  42250. else {
  42251. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42252. }
  42253. }
  42254. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42255. var depth = 1.0;
  42256. if (!this._refractionTexture.isCube) {
  42257. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42258. if (this._refractionTexture.depth) {
  42259. depth = this._refractionTexture.depth;
  42260. }
  42261. }
  42262. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42263. }
  42264. }
  42265. // Point size
  42266. if (this.pointsCloud) {
  42267. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42268. }
  42269. if (defines.SPECULARTERM) {
  42270. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42271. }
  42272. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42273. // Diffuse
  42274. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42275. }
  42276. // Textures
  42277. if (scene.texturesEnabled) {
  42278. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42279. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42280. }
  42281. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42282. effect.setTexture("ambientSampler", this._ambientTexture);
  42283. }
  42284. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42285. effect.setTexture("opacitySampler", this._opacityTexture);
  42286. }
  42287. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42288. if (this._reflectionTexture.isCube) {
  42289. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42290. }
  42291. else {
  42292. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42293. }
  42294. }
  42295. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42296. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42297. }
  42298. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42299. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42300. }
  42301. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42302. effect.setTexture("specularSampler", this._specularTexture);
  42303. }
  42304. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42305. effect.setTexture("bumpSampler", this._bumpTexture);
  42306. }
  42307. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42308. var depth = 1.0;
  42309. if (this._refractionTexture.isCube) {
  42310. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42311. }
  42312. else {
  42313. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42314. }
  42315. }
  42316. }
  42317. // Clip plane
  42318. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42319. // Colors
  42320. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42321. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42322. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42323. }
  42324. if (mustRebind || !this.isFrozen) {
  42325. // Lights
  42326. if (scene.lightsEnabled && !this._disableLighting) {
  42327. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42328. }
  42329. // View
  42330. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42331. this.bindView(effect);
  42332. }
  42333. // Fog
  42334. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42335. // Morph targets
  42336. if (defines.NUM_MORPH_INFLUENCERS) {
  42337. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42338. }
  42339. // Log. depth
  42340. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42341. // image processing
  42342. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42343. this._imageProcessingConfiguration.bind(this._activeEffect);
  42344. }
  42345. }
  42346. this._uniformBuffer.update();
  42347. this._afterBind(mesh, this._activeEffect);
  42348. };
  42349. StandardMaterial.prototype.getAnimatables = function () {
  42350. var results = [];
  42351. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42352. results.push(this._diffuseTexture);
  42353. }
  42354. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42355. results.push(this._ambientTexture);
  42356. }
  42357. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42358. results.push(this._opacityTexture);
  42359. }
  42360. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42361. results.push(this._reflectionTexture);
  42362. }
  42363. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42364. results.push(this._emissiveTexture);
  42365. }
  42366. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42367. results.push(this._specularTexture);
  42368. }
  42369. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42370. results.push(this._bumpTexture);
  42371. }
  42372. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42373. results.push(this._lightmapTexture);
  42374. }
  42375. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42376. results.push(this._refractionTexture);
  42377. }
  42378. return results;
  42379. };
  42380. StandardMaterial.prototype.getActiveTextures = function () {
  42381. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42382. if (this._diffuseTexture) {
  42383. activeTextures.push(this._diffuseTexture);
  42384. }
  42385. if (this._ambientTexture) {
  42386. activeTextures.push(this._ambientTexture);
  42387. }
  42388. if (this._opacityTexture) {
  42389. activeTextures.push(this._opacityTexture);
  42390. }
  42391. if (this._reflectionTexture) {
  42392. activeTextures.push(this._reflectionTexture);
  42393. }
  42394. if (this._emissiveTexture) {
  42395. activeTextures.push(this._emissiveTexture);
  42396. }
  42397. if (this._specularTexture) {
  42398. activeTextures.push(this._specularTexture);
  42399. }
  42400. if (this._bumpTexture) {
  42401. activeTextures.push(this._bumpTexture);
  42402. }
  42403. if (this._lightmapTexture) {
  42404. activeTextures.push(this._lightmapTexture);
  42405. }
  42406. if (this._refractionTexture) {
  42407. activeTextures.push(this._refractionTexture);
  42408. }
  42409. return activeTextures;
  42410. };
  42411. StandardMaterial.prototype.hasTexture = function (texture) {
  42412. if (_super.prototype.hasTexture.call(this, texture)) {
  42413. return true;
  42414. }
  42415. if (this._diffuseTexture === texture) {
  42416. return true;
  42417. }
  42418. if (this._ambientTexture === texture) {
  42419. return true;
  42420. }
  42421. if (this._opacityTexture === texture) {
  42422. return true;
  42423. }
  42424. if (this._reflectionTexture === texture) {
  42425. return true;
  42426. }
  42427. if (this._emissiveTexture === texture) {
  42428. return true;
  42429. }
  42430. if (this._specularTexture === texture) {
  42431. return true;
  42432. }
  42433. if (this._bumpTexture === texture) {
  42434. return true;
  42435. }
  42436. if (this._lightmapTexture === texture) {
  42437. return true;
  42438. }
  42439. if (this._refractionTexture === texture) {
  42440. return true;
  42441. }
  42442. return false;
  42443. };
  42444. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42445. if (forceDisposeTextures) {
  42446. if (this._diffuseTexture) {
  42447. this._diffuseTexture.dispose();
  42448. }
  42449. if (this._ambientTexture) {
  42450. this._ambientTexture.dispose();
  42451. }
  42452. if (this._opacityTexture) {
  42453. this._opacityTexture.dispose();
  42454. }
  42455. if (this._reflectionTexture) {
  42456. this._reflectionTexture.dispose();
  42457. }
  42458. if (this._emissiveTexture) {
  42459. this._emissiveTexture.dispose();
  42460. }
  42461. if (this._specularTexture) {
  42462. this._specularTexture.dispose();
  42463. }
  42464. if (this._bumpTexture) {
  42465. this._bumpTexture.dispose();
  42466. }
  42467. if (this._lightmapTexture) {
  42468. this._lightmapTexture.dispose();
  42469. }
  42470. if (this._refractionTexture) {
  42471. this._refractionTexture.dispose();
  42472. }
  42473. }
  42474. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42475. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42476. }
  42477. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42478. };
  42479. StandardMaterial.prototype.clone = function (name) {
  42480. var _this = this;
  42481. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42482. result.name = name;
  42483. result.id = name;
  42484. return result;
  42485. };
  42486. StandardMaterial.prototype.serialize = function () {
  42487. return BABYLON.SerializationHelper.Serialize(this);
  42488. };
  42489. // Statics
  42490. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42491. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42492. };
  42493. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42494. get: function () {
  42495. return StandardMaterial._DiffuseTextureEnabled;
  42496. },
  42497. set: function (value) {
  42498. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42499. return;
  42500. }
  42501. StandardMaterial._DiffuseTextureEnabled = value;
  42502. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42503. },
  42504. enumerable: true,
  42505. configurable: true
  42506. });
  42507. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42508. get: function () {
  42509. return StandardMaterial._AmbientTextureEnabled;
  42510. },
  42511. set: function (value) {
  42512. if (StandardMaterial._AmbientTextureEnabled === value) {
  42513. return;
  42514. }
  42515. StandardMaterial._AmbientTextureEnabled = value;
  42516. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42517. },
  42518. enumerable: true,
  42519. configurable: true
  42520. });
  42521. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42522. get: function () {
  42523. return StandardMaterial._OpacityTextureEnabled;
  42524. },
  42525. set: function (value) {
  42526. if (StandardMaterial._OpacityTextureEnabled === value) {
  42527. return;
  42528. }
  42529. StandardMaterial._OpacityTextureEnabled = value;
  42530. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42531. },
  42532. enumerable: true,
  42533. configurable: true
  42534. });
  42535. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42536. get: function () {
  42537. return StandardMaterial._ReflectionTextureEnabled;
  42538. },
  42539. set: function (value) {
  42540. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42541. return;
  42542. }
  42543. StandardMaterial._ReflectionTextureEnabled = value;
  42544. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42545. },
  42546. enumerable: true,
  42547. configurable: true
  42548. });
  42549. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42550. get: function () {
  42551. return StandardMaterial._EmissiveTextureEnabled;
  42552. },
  42553. set: function (value) {
  42554. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42555. return;
  42556. }
  42557. StandardMaterial._EmissiveTextureEnabled = value;
  42558. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42559. },
  42560. enumerable: true,
  42561. configurable: true
  42562. });
  42563. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42564. get: function () {
  42565. return StandardMaterial._SpecularTextureEnabled;
  42566. },
  42567. set: function (value) {
  42568. if (StandardMaterial._SpecularTextureEnabled === value) {
  42569. return;
  42570. }
  42571. StandardMaterial._SpecularTextureEnabled = value;
  42572. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42573. },
  42574. enumerable: true,
  42575. configurable: true
  42576. });
  42577. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42578. get: function () {
  42579. return StandardMaterial._BumpTextureEnabled;
  42580. },
  42581. set: function (value) {
  42582. if (StandardMaterial._BumpTextureEnabled === value) {
  42583. return;
  42584. }
  42585. StandardMaterial._BumpTextureEnabled = value;
  42586. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42587. },
  42588. enumerable: true,
  42589. configurable: true
  42590. });
  42591. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42592. get: function () {
  42593. return StandardMaterial._LightmapTextureEnabled;
  42594. },
  42595. set: function (value) {
  42596. if (StandardMaterial._LightmapTextureEnabled === value) {
  42597. return;
  42598. }
  42599. StandardMaterial._LightmapTextureEnabled = value;
  42600. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42601. },
  42602. enumerable: true,
  42603. configurable: true
  42604. });
  42605. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42606. get: function () {
  42607. return StandardMaterial._RefractionTextureEnabled;
  42608. },
  42609. set: function (value) {
  42610. if (StandardMaterial._RefractionTextureEnabled === value) {
  42611. return;
  42612. }
  42613. StandardMaterial._RefractionTextureEnabled = value;
  42614. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42615. },
  42616. enumerable: true,
  42617. configurable: true
  42618. });
  42619. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42620. get: function () {
  42621. return StandardMaterial._ColorGradingTextureEnabled;
  42622. },
  42623. set: function (value) {
  42624. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42625. return;
  42626. }
  42627. StandardMaterial._ColorGradingTextureEnabled = value;
  42628. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42629. },
  42630. enumerable: true,
  42631. configurable: true
  42632. });
  42633. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42634. get: function () {
  42635. return StandardMaterial._FresnelEnabled;
  42636. },
  42637. set: function (value) {
  42638. if (StandardMaterial._FresnelEnabled === value) {
  42639. return;
  42640. }
  42641. StandardMaterial._FresnelEnabled = value;
  42642. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42643. },
  42644. enumerable: true,
  42645. configurable: true
  42646. });
  42647. // Flags used to enable or disable a type of texture for all Standard Materials
  42648. StandardMaterial._DiffuseTextureEnabled = true;
  42649. StandardMaterial._AmbientTextureEnabled = true;
  42650. StandardMaterial._OpacityTextureEnabled = true;
  42651. StandardMaterial._ReflectionTextureEnabled = true;
  42652. StandardMaterial._EmissiveTextureEnabled = true;
  42653. StandardMaterial._SpecularTextureEnabled = true;
  42654. StandardMaterial._BumpTextureEnabled = true;
  42655. StandardMaterial._LightmapTextureEnabled = true;
  42656. StandardMaterial._RefractionTextureEnabled = true;
  42657. StandardMaterial._ColorGradingTextureEnabled = true;
  42658. StandardMaterial._FresnelEnabled = true;
  42659. __decorate([
  42660. BABYLON.serializeAsTexture("diffuseTexture")
  42661. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42662. __decorate([
  42663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42664. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42665. __decorate([
  42666. BABYLON.serializeAsTexture("ambientTexture")
  42667. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42668. __decorate([
  42669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42670. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42671. __decorate([
  42672. BABYLON.serializeAsTexture("opacityTexture")
  42673. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42674. __decorate([
  42675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42676. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42677. __decorate([
  42678. BABYLON.serializeAsTexture("reflectionTexture")
  42679. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42680. __decorate([
  42681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42682. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42683. __decorate([
  42684. BABYLON.serializeAsTexture("emissiveTexture")
  42685. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42686. __decorate([
  42687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42688. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42689. __decorate([
  42690. BABYLON.serializeAsTexture("specularTexture")
  42691. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42692. __decorate([
  42693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42694. ], StandardMaterial.prototype, "specularTexture", void 0);
  42695. __decorate([
  42696. BABYLON.serializeAsTexture("bumpTexture")
  42697. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42698. __decorate([
  42699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42700. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42701. __decorate([
  42702. BABYLON.serializeAsTexture("lightmapTexture")
  42703. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42704. __decorate([
  42705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42706. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42707. __decorate([
  42708. BABYLON.serializeAsTexture("refractionTexture")
  42709. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42710. __decorate([
  42711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42712. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42713. __decorate([
  42714. BABYLON.serializeAsColor3("ambient")
  42715. ], StandardMaterial.prototype, "ambientColor", void 0);
  42716. __decorate([
  42717. BABYLON.serializeAsColor3("diffuse")
  42718. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42719. __decorate([
  42720. BABYLON.serializeAsColor3("specular")
  42721. ], StandardMaterial.prototype, "specularColor", void 0);
  42722. __decorate([
  42723. BABYLON.serializeAsColor3("emissive")
  42724. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42725. __decorate([
  42726. BABYLON.serialize()
  42727. ], StandardMaterial.prototype, "specularPower", void 0);
  42728. __decorate([
  42729. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42730. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42731. __decorate([
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42734. __decorate([
  42735. BABYLON.serialize("useEmissiveAsIllumination")
  42736. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42737. __decorate([
  42738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42739. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42740. __decorate([
  42741. BABYLON.serialize("linkEmissiveWithDiffuse")
  42742. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42743. __decorate([
  42744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42745. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42746. __decorate([
  42747. BABYLON.serialize("useSpecularOverAlpha")
  42748. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42749. __decorate([
  42750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42751. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42752. __decorate([
  42753. BABYLON.serialize("useReflectionOverAlpha")
  42754. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42755. __decorate([
  42756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42757. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42758. __decorate([
  42759. BABYLON.serialize("disableLighting")
  42760. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42761. __decorate([
  42762. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42763. ], StandardMaterial.prototype, "disableLighting", void 0);
  42764. __decorate([
  42765. BABYLON.serialize("useObjectSpaceNormalMap")
  42766. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42767. __decorate([
  42768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42769. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42770. __decorate([
  42771. BABYLON.serialize("useParallax")
  42772. ], StandardMaterial.prototype, "_useParallax", void 0);
  42773. __decorate([
  42774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42775. ], StandardMaterial.prototype, "useParallax", void 0);
  42776. __decorate([
  42777. BABYLON.serialize("useParallaxOcclusion")
  42778. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42779. __decorate([
  42780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42781. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42782. __decorate([
  42783. BABYLON.serialize()
  42784. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42785. __decorate([
  42786. BABYLON.serialize("roughness")
  42787. ], StandardMaterial.prototype, "_roughness", void 0);
  42788. __decorate([
  42789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42790. ], StandardMaterial.prototype, "roughness", void 0);
  42791. __decorate([
  42792. BABYLON.serialize()
  42793. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42794. __decorate([
  42795. BABYLON.serialize()
  42796. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42797. __decorate([
  42798. BABYLON.serialize()
  42799. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42800. __decorate([
  42801. BABYLON.serialize("useLightmapAsShadowmap")
  42802. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42803. __decorate([
  42804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42805. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42806. __decorate([
  42807. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42808. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42809. __decorate([
  42810. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42811. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42812. __decorate([
  42813. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42814. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42815. __decorate([
  42816. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42817. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42818. __decorate([
  42819. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42820. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42821. __decorate([
  42822. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42823. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42824. __decorate([
  42825. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42826. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42827. __decorate([
  42828. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42829. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42830. __decorate([
  42831. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42832. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42833. __decorate([
  42834. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42835. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42836. __decorate([
  42837. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42838. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42839. __decorate([
  42840. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42841. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42842. __decorate([
  42843. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42844. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42845. __decorate([
  42846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42847. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42848. __decorate([
  42849. BABYLON.serialize("maxSimultaneousLights")
  42850. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42851. __decorate([
  42852. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42853. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42854. __decorate([
  42855. BABYLON.serialize("invertNormalMapX")
  42856. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42857. __decorate([
  42858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42859. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42860. __decorate([
  42861. BABYLON.serialize("invertNormalMapY")
  42862. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42863. __decorate([
  42864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42865. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42866. __decorate([
  42867. BABYLON.serialize("twoSidedLighting")
  42868. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42869. __decorate([
  42870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42871. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42872. __decorate([
  42873. BABYLON.serialize()
  42874. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42875. return StandardMaterial;
  42876. }(BABYLON.PushMaterial));
  42877. BABYLON.StandardMaterial = StandardMaterial;
  42878. })(BABYLON || (BABYLON = {}));
  42879. //# sourceMappingURL=babylon.standardMaterial.js.map
  42880. var BABYLON;
  42881. (function (BABYLON) {
  42882. /**
  42883. * Class representing spherical polynomial coefficients to the 3rd degree
  42884. */
  42885. var SphericalPolynomial = /** @class */ (function () {
  42886. function SphericalPolynomial() {
  42887. /**
  42888. * The x coefficients of the spherical polynomial
  42889. */
  42890. this.x = BABYLON.Vector3.Zero();
  42891. /**
  42892. * The y coefficients of the spherical polynomial
  42893. */
  42894. this.y = BABYLON.Vector3.Zero();
  42895. /**
  42896. * The z coefficients of the spherical polynomial
  42897. */
  42898. this.z = BABYLON.Vector3.Zero();
  42899. /**
  42900. * The xx coefficients of the spherical polynomial
  42901. */
  42902. this.xx = BABYLON.Vector3.Zero();
  42903. /**
  42904. * The yy coefficients of the spherical polynomial
  42905. */
  42906. this.yy = BABYLON.Vector3.Zero();
  42907. /**
  42908. * The zz coefficients of the spherical polynomial
  42909. */
  42910. this.zz = BABYLON.Vector3.Zero();
  42911. /**
  42912. * The xy coefficients of the spherical polynomial
  42913. */
  42914. this.xy = BABYLON.Vector3.Zero();
  42915. /**
  42916. * The yz coefficients of the spherical polynomial
  42917. */
  42918. this.yz = BABYLON.Vector3.Zero();
  42919. /**
  42920. * The zx coefficients of the spherical polynomial
  42921. */
  42922. this.zx = BABYLON.Vector3.Zero();
  42923. }
  42924. /**
  42925. * Adds an ambient color to the spherical polynomial
  42926. * @param color the color to add
  42927. */
  42928. SphericalPolynomial.prototype.addAmbient = function (color) {
  42929. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42930. this.xx = this.xx.add(colorVector);
  42931. this.yy = this.yy.add(colorVector);
  42932. this.zz = this.zz.add(colorVector);
  42933. };
  42934. /**
  42935. * Scales the spherical polynomial by the given amount
  42936. * @param scale the amount to scale
  42937. */
  42938. SphericalPolynomial.prototype.scale = function (scale) {
  42939. this.x = this.x.scale(scale);
  42940. this.y = this.y.scale(scale);
  42941. this.z = this.z.scale(scale);
  42942. this.xx = this.xx.scale(scale);
  42943. this.yy = this.yy.scale(scale);
  42944. this.zz = this.zz.scale(scale);
  42945. this.yz = this.yz.scale(scale);
  42946. this.zx = this.zx.scale(scale);
  42947. this.xy = this.xy.scale(scale);
  42948. };
  42949. /**
  42950. * Gets the spherical polynomial from harmonics
  42951. * @param harmonics the spherical harmonics
  42952. * @returns the spherical polynomial
  42953. */
  42954. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42955. var result = new SphericalPolynomial();
  42956. result.x = harmonics.l11.scale(1.02333);
  42957. result.y = harmonics.l1_1.scale(1.02333);
  42958. result.z = harmonics.l10.scale(1.02333);
  42959. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42960. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42961. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42962. result.yz = harmonics.l2_1.scale(0.858086);
  42963. result.zx = harmonics.l21.scale(0.858086);
  42964. result.xy = harmonics.l2_2.scale(0.858086);
  42965. result.scale(1.0 / Math.PI);
  42966. return result;
  42967. };
  42968. /**
  42969. * Constructs a spherical polynomial from an array.
  42970. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42971. * @returns the spherical polynomial
  42972. */
  42973. SphericalPolynomial.FromArray = function (data) {
  42974. var sp = new SphericalPolynomial();
  42975. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42976. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42977. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42978. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42979. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42980. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42981. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42982. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42983. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42984. return sp;
  42985. };
  42986. return SphericalPolynomial;
  42987. }());
  42988. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42989. /**
  42990. * Class representing spherical harmonics coefficients to the 3rd degree
  42991. */
  42992. var SphericalHarmonics = /** @class */ (function () {
  42993. function SphericalHarmonics() {
  42994. /**
  42995. * The l0,0 coefficients of the spherical harmonics
  42996. */
  42997. this.l00 = BABYLON.Vector3.Zero();
  42998. /**
  42999. * The l1,-1 coefficients of the spherical harmonics
  43000. */
  43001. this.l1_1 = BABYLON.Vector3.Zero();
  43002. /**
  43003. * The l1,0 coefficients of the spherical harmonics
  43004. */
  43005. this.l10 = BABYLON.Vector3.Zero();
  43006. /**
  43007. * The l1,1 coefficients of the spherical harmonics
  43008. */
  43009. this.l11 = BABYLON.Vector3.Zero();
  43010. /**
  43011. * The l2,-2 coefficients of the spherical harmonics
  43012. */
  43013. this.l2_2 = BABYLON.Vector3.Zero();
  43014. /**
  43015. * The l2,-1 coefficients of the spherical harmonics
  43016. */
  43017. this.l2_1 = BABYLON.Vector3.Zero();
  43018. /**
  43019. * The l2,0 coefficients of the spherical harmonics
  43020. */
  43021. this.l20 = BABYLON.Vector3.Zero();
  43022. /**
  43023. * The l2,1 coefficients of the spherical harmonics
  43024. */
  43025. this.l21 = BABYLON.Vector3.Zero();
  43026. /**
  43027. * The l2,2 coefficients of the spherical harmonics
  43028. */
  43029. this.lL22 = BABYLON.Vector3.Zero();
  43030. }
  43031. /**
  43032. * Adds a light to the spherical harmonics
  43033. * @param direction the direction of the light
  43034. * @param color the color of the light
  43035. * @param deltaSolidAngle the delta solid angle of the light
  43036. */
  43037. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43038. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43039. var c = colorVector.scale(deltaSolidAngle);
  43040. this.l00 = this.l00.add(c.scale(0.282095));
  43041. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43042. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43043. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43044. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43045. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43046. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43047. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43048. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43049. };
  43050. /**
  43051. * Scales the spherical harmonics by the given amount
  43052. * @param scale the amount to scale
  43053. */
  43054. SphericalHarmonics.prototype.scale = function (scale) {
  43055. this.l00 = this.l00.scale(scale);
  43056. this.l1_1 = this.l1_1.scale(scale);
  43057. this.l10 = this.l10.scale(scale);
  43058. this.l11 = this.l11.scale(scale);
  43059. this.l2_2 = this.l2_2.scale(scale);
  43060. this.l2_1 = this.l2_1.scale(scale);
  43061. this.l20 = this.l20.scale(scale);
  43062. this.l21 = this.l21.scale(scale);
  43063. this.lL22 = this.lL22.scale(scale);
  43064. };
  43065. /**
  43066. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43067. *
  43068. * ```
  43069. * E_lm = A_l * L_lm
  43070. * ```
  43071. *
  43072. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43073. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43074. * the scaling factors are given in equation 9.
  43075. */
  43076. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43077. // Constant (Band 0)
  43078. this.l00 = this.l00.scale(3.141593);
  43079. // Linear (Band 1)
  43080. this.l1_1 = this.l1_1.scale(2.094395);
  43081. this.l10 = this.l10.scale(2.094395);
  43082. this.l11 = this.l11.scale(2.094395);
  43083. // Quadratic (Band 2)
  43084. this.l2_2 = this.l2_2.scale(0.785398);
  43085. this.l2_1 = this.l2_1.scale(0.785398);
  43086. this.l20 = this.l20.scale(0.785398);
  43087. this.l21 = this.l21.scale(0.785398);
  43088. this.lL22 = this.lL22.scale(0.785398);
  43089. };
  43090. /**
  43091. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43092. *
  43093. * ```
  43094. * L = (1/pi) * E * rho
  43095. * ```
  43096. *
  43097. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43098. */
  43099. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43100. this.scale(1.0 / Math.PI);
  43101. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43102. // (The pixel shader must apply albedo after texture fetches, etc).
  43103. };
  43104. /**
  43105. * Gets the spherical harmonics from polynomial
  43106. * @param polynomial the spherical polynomial
  43107. * @returns the spherical harmonics
  43108. */
  43109. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43110. var result = new SphericalHarmonics();
  43111. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43112. result.l1_1 = polynomial.y.scale(0.977204);
  43113. result.l10 = polynomial.z.scale(0.977204);
  43114. result.l11 = polynomial.x.scale(0.977204);
  43115. result.l2_2 = polynomial.xy.scale(1.16538);
  43116. result.l2_1 = polynomial.yz.scale(1.16538);
  43117. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43118. result.l21 = polynomial.zx.scale(1.16538);
  43119. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43120. result.scale(Math.PI);
  43121. return result;
  43122. };
  43123. /**
  43124. * Constructs a spherical harmonics from an array.
  43125. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43126. * @returns the spherical harmonics
  43127. */
  43128. SphericalHarmonics.FromArray = function (data) {
  43129. var sh = new SphericalHarmonics();
  43130. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43131. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43132. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43133. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43134. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43135. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43136. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43137. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43138. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43139. return sh;
  43140. };
  43141. return SphericalHarmonics;
  43142. }());
  43143. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43144. })(BABYLON || (BABYLON = {}));
  43145. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43146. var BABYLON;
  43147. (function (BABYLON) {
  43148. var FileFaceOrientation = /** @class */ (function () {
  43149. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43150. this.name = name;
  43151. this.worldAxisForNormal = worldAxisForNormal;
  43152. this.worldAxisForFileX = worldAxisForFileX;
  43153. this.worldAxisForFileY = worldAxisForFileY;
  43154. }
  43155. return FileFaceOrientation;
  43156. }());
  43157. ;
  43158. /**
  43159. * Helper class dealing with the extraction of spherical polynomial dataArray
  43160. * from a cube map.
  43161. */
  43162. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43163. function CubeMapToSphericalPolynomialTools() {
  43164. }
  43165. /**
  43166. * Converts a texture to the according Spherical Polynomial data.
  43167. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43168. *
  43169. * @param texture The texture to extract the information from.
  43170. * @return The Spherical Polynomial data.
  43171. */
  43172. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43173. if (!texture.isCube) {
  43174. // Only supports cube Textures currently.
  43175. return null;
  43176. }
  43177. var size = texture.getSize().width;
  43178. var right = texture.readPixels(0);
  43179. var left = texture.readPixels(1);
  43180. var up;
  43181. var down;
  43182. if (texture.isRenderTarget) {
  43183. up = texture.readPixels(3);
  43184. down = texture.readPixels(2);
  43185. }
  43186. else {
  43187. up = texture.readPixels(2);
  43188. down = texture.readPixels(3);
  43189. }
  43190. var front = texture.readPixels(4);
  43191. var back = texture.readPixels(5);
  43192. var gammaSpace = texture.gammaSpace;
  43193. // Always read as RGBA.
  43194. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43195. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43196. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43197. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43198. }
  43199. var cubeInfo = {
  43200. size: size,
  43201. right: right,
  43202. left: left,
  43203. up: up,
  43204. down: down,
  43205. front: front,
  43206. back: back,
  43207. format: format,
  43208. type: type,
  43209. gammaSpace: gammaSpace,
  43210. };
  43211. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43212. };
  43213. /**
  43214. * Converts a cubemap to the according Spherical Polynomial data.
  43215. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43216. *
  43217. * @param cubeInfo The Cube map to extract the information from.
  43218. * @return The Spherical Polynomial data.
  43219. */
  43220. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43221. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43222. var totalSolidAngle = 0.0;
  43223. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43224. var du = 2.0 / cubeInfo.size;
  43225. var dv = du;
  43226. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43227. var minUV = du * 0.5 - 1.0;
  43228. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43229. var fileFace = this.FileFaces[faceIndex];
  43230. var dataArray = cubeInfo[fileFace.name];
  43231. var v = minUV;
  43232. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43233. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43234. // Because SP is still linear, so summation is fine in that basis.
  43235. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43236. for (var y = 0; y < cubeInfo.size; y++) {
  43237. var u = minUV;
  43238. for (var x = 0; x < cubeInfo.size; x++) {
  43239. // World direction (not normalised)
  43240. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43241. worldDirection.normalize();
  43242. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43243. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43244. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43245. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43246. // Handle Integer types.
  43247. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43248. r /= 255;
  43249. g /= 255;
  43250. b /= 255;
  43251. }
  43252. // Handle Gamma space textures.
  43253. if (cubeInfo.gammaSpace) {
  43254. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43255. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43256. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43257. }
  43258. var color = new BABYLON.Color3(r, g, b);
  43259. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43260. totalSolidAngle += deltaSolidAngle;
  43261. u += du;
  43262. }
  43263. v += dv;
  43264. }
  43265. }
  43266. // Solid angle for entire sphere is 4*pi
  43267. var sphereSolidAngle = 4.0 * Math.PI;
  43268. // Adjust the solid angle to allow for how many faces we processed.
  43269. var facesProcessed = 6.0;
  43270. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43271. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43272. // This is needed because the numerical integration over the cube uses a
  43273. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43274. // and also to compensate for accumulative error due to float precision in the summation.
  43275. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43276. sphericalHarmonics.scale(correctionFactor);
  43277. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43278. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43279. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43280. };
  43281. CubeMapToSphericalPolynomialTools.FileFaces = [
  43282. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43283. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43284. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43285. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43286. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43287. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43288. ];
  43289. return CubeMapToSphericalPolynomialTools;
  43290. }());
  43291. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43292. })(BABYLON || (BABYLON = {}));
  43293. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43294. var BABYLON;
  43295. (function (BABYLON) {
  43296. /**
  43297. * Manages the defines for the PBR Material.
  43298. * @hiddenChildren
  43299. */
  43300. var PBRMaterialDefines = /** @class */ (function (_super) {
  43301. __extends(PBRMaterialDefines, _super);
  43302. /**
  43303. * Initializes the PBR Material defines.
  43304. */
  43305. function PBRMaterialDefines() {
  43306. var _this = _super.call(this) || this;
  43307. _this.PBR = true;
  43308. _this.MAINUV1 = false;
  43309. _this.MAINUV2 = false;
  43310. _this.UV1 = false;
  43311. _this.UV2 = false;
  43312. _this.ALBEDO = false;
  43313. _this.ALBEDODIRECTUV = 0;
  43314. _this.VERTEXCOLOR = false;
  43315. _this.AMBIENT = false;
  43316. _this.AMBIENTDIRECTUV = 0;
  43317. _this.AMBIENTINGRAYSCALE = false;
  43318. _this.OPACITY = false;
  43319. _this.VERTEXALPHA = false;
  43320. _this.OPACITYDIRECTUV = 0;
  43321. _this.OPACITYRGB = false;
  43322. _this.ALPHATEST = false;
  43323. _this.DEPTHPREPASS = false;
  43324. _this.ALPHABLEND = false;
  43325. _this.ALPHAFROMALBEDO = false;
  43326. _this.ALPHATESTVALUE = "0.5";
  43327. _this.SPECULAROVERALPHA = false;
  43328. _this.RADIANCEOVERALPHA = false;
  43329. _this.ALPHAFRESNEL = false;
  43330. _this.LINEARALPHAFRESNEL = false;
  43331. _this.PREMULTIPLYALPHA = false;
  43332. _this.EMISSIVE = false;
  43333. _this.EMISSIVEDIRECTUV = 0;
  43334. _this.REFLECTIVITY = false;
  43335. _this.REFLECTIVITYDIRECTUV = 0;
  43336. _this.SPECULARTERM = false;
  43337. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43338. _this.MICROSURFACEAUTOMATIC = false;
  43339. _this.LODBASEDMICROSFURACE = false;
  43340. _this.MICROSURFACEMAP = false;
  43341. _this.MICROSURFACEMAPDIRECTUV = 0;
  43342. _this.METALLICWORKFLOW = false;
  43343. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43344. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43345. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43346. _this.AOSTOREINMETALMAPRED = false;
  43347. _this.ENVIRONMENTBRDF = false;
  43348. _this.NORMAL = false;
  43349. _this.TANGENT = false;
  43350. _this.BUMP = false;
  43351. _this.BUMPDIRECTUV = 0;
  43352. _this.OBJECTSPACE_NORMALMAP = false;
  43353. _this.PARALLAX = false;
  43354. _this.PARALLAXOCCLUSION = false;
  43355. _this.NORMALXYSCALE = true;
  43356. _this.LIGHTMAP = false;
  43357. _this.LIGHTMAPDIRECTUV = 0;
  43358. _this.USELIGHTMAPASSHADOWMAP = false;
  43359. _this.GAMMALIGHTMAP = false;
  43360. _this.REFLECTION = false;
  43361. _this.REFLECTIONMAP_3D = false;
  43362. _this.REFLECTIONMAP_SPHERICAL = false;
  43363. _this.REFLECTIONMAP_PLANAR = false;
  43364. _this.REFLECTIONMAP_CUBIC = false;
  43365. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43366. _this.REFLECTIONMAP_PROJECTION = false;
  43367. _this.REFLECTIONMAP_SKYBOX = false;
  43368. _this.REFLECTIONMAP_EXPLICIT = false;
  43369. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43370. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43371. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43372. _this.INVERTCUBICMAP = false;
  43373. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43374. _this.USESPHERICALINVERTEX = false;
  43375. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43376. _this.LODINREFLECTIONALPHA = false;
  43377. _this.GAMMAREFLECTION = false;
  43378. _this.RGBDREFLECTION = false;
  43379. _this.RADIANCEOCCLUSION = false;
  43380. _this.HORIZONOCCLUSION = false;
  43381. _this.REFRACTION = false;
  43382. _this.REFRACTIONMAP_3D = false;
  43383. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43384. _this.LODINREFRACTIONALPHA = false;
  43385. _this.GAMMAREFRACTION = false;
  43386. _this.RGBDREFRACTION = false;
  43387. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43388. _this.INSTANCES = false;
  43389. _this.NUM_BONE_INFLUENCERS = 0;
  43390. _this.BonesPerMesh = 0;
  43391. _this.NONUNIFORMSCALING = false;
  43392. _this.MORPHTARGETS = false;
  43393. _this.MORPHTARGETS_NORMAL = false;
  43394. _this.MORPHTARGETS_TANGENT = false;
  43395. _this.NUM_MORPH_INFLUENCERS = 0;
  43396. _this.IMAGEPROCESSING = false;
  43397. _this.VIGNETTE = false;
  43398. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43399. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43400. _this.TONEMAPPING = false;
  43401. _this.CONTRAST = false;
  43402. _this.COLORCURVES = false;
  43403. _this.COLORGRADING = false;
  43404. _this.COLORGRADING3D = false;
  43405. _this.SAMPLER3DGREENDEPTH = false;
  43406. _this.SAMPLER3DBGRMAP = false;
  43407. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43408. _this.EXPOSURE = false;
  43409. _this.USEPHYSICALLIGHTFALLOFF = false;
  43410. _this.USEGLTFLIGHTFALLOFF = false;
  43411. _this.TWOSIDEDLIGHTING = false;
  43412. _this.SHADOWFLOAT = false;
  43413. _this.CLIPPLANE = false;
  43414. _this.POINTSIZE = false;
  43415. _this.FOG = false;
  43416. _this.LOGARITHMICDEPTH = false;
  43417. _this.FORCENORMALFORWARD = false;
  43418. _this.SPECULARAA = false;
  43419. _this.UNLIT = false;
  43420. _this.rebuild();
  43421. return _this;
  43422. }
  43423. /**
  43424. * Resets the PBR Material defines.
  43425. */
  43426. PBRMaterialDefines.prototype.reset = function () {
  43427. _super.prototype.reset.call(this);
  43428. this.ALPHATESTVALUE = "0.5";
  43429. this.PBR = true;
  43430. };
  43431. return PBRMaterialDefines;
  43432. }(BABYLON.MaterialDefines));
  43433. /**
  43434. * The Physically based material base class of BJS.
  43435. *
  43436. * This offers the main features of a standard PBR material.
  43437. * For more information, please refer to the documentation :
  43438. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43439. */
  43440. var PBRBaseMaterial = /** @class */ (function (_super) {
  43441. __extends(PBRBaseMaterial, _super);
  43442. /**
  43443. * Instantiates a new PBRMaterial instance.
  43444. *
  43445. * @param name The material name
  43446. * @param scene The scene the material will be use in.
  43447. */
  43448. function PBRBaseMaterial(name, scene) {
  43449. var _this = _super.call(this, name, scene) || this;
  43450. /**
  43451. * Intensity of the direct lights e.g. the four lights available in your scene.
  43452. * This impacts both the direct diffuse and specular highlights.
  43453. */
  43454. _this._directIntensity = 1.0;
  43455. /**
  43456. * Intensity of the emissive part of the material.
  43457. * This helps controlling the emissive effect without modifying the emissive color.
  43458. */
  43459. _this._emissiveIntensity = 1.0;
  43460. /**
  43461. * Intensity of the environment e.g. how much the environment will light the object
  43462. * either through harmonics for rough material or through the refelction for shiny ones.
  43463. */
  43464. _this._environmentIntensity = 1.0;
  43465. /**
  43466. * This is a special control allowing the reduction of the specular highlights coming from the
  43467. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43468. */
  43469. _this._specularIntensity = 1.0;
  43470. /**
  43471. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43472. */
  43473. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43474. /**
  43475. * Debug Control allowing disabling the bump map on this material.
  43476. */
  43477. _this._disableBumpMap = false;
  43478. /**
  43479. * AKA Occlusion Texture Intensity in other nomenclature.
  43480. */
  43481. _this._ambientTextureStrength = 1.0;
  43482. /**
  43483. * The color of a material in ambient lighting.
  43484. */
  43485. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43486. /**
  43487. * AKA Diffuse Color in other nomenclature.
  43488. */
  43489. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43490. /**
  43491. * AKA Specular Color in other nomenclature.
  43492. */
  43493. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43494. /**
  43495. * The color applied when light is reflected from a material.
  43496. */
  43497. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43498. /**
  43499. * The color applied when light is emitted from a material.
  43500. */
  43501. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43502. /**
  43503. * AKA Glossiness in other nomenclature.
  43504. */
  43505. _this._microSurface = 0.9;
  43506. /**
  43507. * source material index of refraction (IOR)' / 'destination material IOR.
  43508. */
  43509. _this._indexOfRefraction = 0.66;
  43510. /**
  43511. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43512. */
  43513. _this._invertRefractionY = false;
  43514. /**
  43515. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43516. * Materials half opaque for instance using refraction could benefit from this control.
  43517. */
  43518. _this._linkRefractionWithTransparency = false;
  43519. /**
  43520. * Specifies that the material will use the light map as a show map.
  43521. */
  43522. _this._useLightmapAsShadowmap = false;
  43523. /**
  43524. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43525. * makes the reflect vector face the model (under horizon).
  43526. */
  43527. _this._useHorizonOcclusion = true;
  43528. /**
  43529. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43530. * too much the area relying on ambient texture to define their ambient occlusion.
  43531. */
  43532. _this._useRadianceOcclusion = true;
  43533. /**
  43534. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43535. */
  43536. _this._useAlphaFromAlbedoTexture = false;
  43537. /**
  43538. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43539. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43540. */
  43541. _this._useSpecularOverAlpha = true;
  43542. /**
  43543. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43544. */
  43545. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43546. /**
  43547. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43548. */
  43549. _this._useRoughnessFromMetallicTextureAlpha = true;
  43550. /**
  43551. * Specifies if the metallic texture contains the roughness information in its green channel.
  43552. */
  43553. _this._useRoughnessFromMetallicTextureGreen = false;
  43554. /**
  43555. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43556. */
  43557. _this._useMetallnessFromMetallicTextureBlue = false;
  43558. /**
  43559. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43560. */
  43561. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43562. /**
  43563. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43564. */
  43565. _this._useAmbientInGrayScale = false;
  43566. /**
  43567. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43568. * The material will try to infer what glossiness each pixel should be.
  43569. */
  43570. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43571. /**
  43572. * Defines the falloff type used in this material.
  43573. * It by default is Physical.
  43574. */
  43575. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43576. /**
  43577. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43578. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43579. */
  43580. _this._useRadianceOverAlpha = true;
  43581. /**
  43582. * Allows using an object space normal map (instead of tangent space).
  43583. */
  43584. _this._useObjectSpaceNormalMap = false;
  43585. /**
  43586. * Allows using the bump map in parallax mode.
  43587. */
  43588. _this._useParallax = false;
  43589. /**
  43590. * Allows using the bump map in parallax occlusion mode.
  43591. */
  43592. _this._useParallaxOcclusion = false;
  43593. /**
  43594. * Controls the scale bias of the parallax mode.
  43595. */
  43596. _this._parallaxScaleBias = 0.05;
  43597. /**
  43598. * If sets to true, disables all the lights affecting the material.
  43599. */
  43600. _this._disableLighting = false;
  43601. /**
  43602. * Number of Simultaneous lights allowed on the material.
  43603. */
  43604. _this._maxSimultaneousLights = 4;
  43605. /**
  43606. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43607. */
  43608. _this._invertNormalMapX = false;
  43609. /**
  43610. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43611. */
  43612. _this._invertNormalMapY = false;
  43613. /**
  43614. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43615. */
  43616. _this._twoSidedLighting = false;
  43617. /**
  43618. * Defines the alpha limits in alpha test mode.
  43619. */
  43620. _this._alphaCutOff = 0.4;
  43621. /**
  43622. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43623. */
  43624. _this._forceAlphaTest = false;
  43625. /**
  43626. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43627. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43628. */
  43629. _this._useAlphaFresnel = false;
  43630. /**
  43631. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43632. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43633. */
  43634. _this._useLinearAlphaFresnel = false;
  43635. /**
  43636. * The transparency mode of the material.
  43637. */
  43638. _this._transparencyMode = null;
  43639. /**
  43640. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43641. * from cos thetav and roughness:
  43642. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43643. */
  43644. _this._environmentBRDFTexture = null;
  43645. /**
  43646. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43647. */
  43648. _this._forceIrradianceInFragment = false;
  43649. /**
  43650. * Force normal to face away from face.
  43651. */
  43652. _this._forceNormalForward = false;
  43653. /**
  43654. * Enables specular anti aliasing in the PBR shader.
  43655. * It will both interacts on the Geometry for analytical and IBL lighting.
  43656. * It also prefilter the roughness map based on the bump values.
  43657. */
  43658. _this._enableSpecularAntiAliasing = false;
  43659. /**
  43660. * Stores the available render targets.
  43661. */
  43662. _this._renderTargets = new BABYLON.SmartArray(16);
  43663. /**
  43664. * Sets the global ambient color for the material used in lighting calculations.
  43665. */
  43666. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43667. /**
  43668. * If set to true, no lighting calculations will be applied.
  43669. */
  43670. _this._unlit = false;
  43671. // Setup the default processing configuration to the scene.
  43672. _this._attachImageProcessingConfiguration(null);
  43673. _this.getRenderTargetTextures = function () {
  43674. _this._renderTargets.reset();
  43675. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43676. _this._renderTargets.push(_this._reflectionTexture);
  43677. }
  43678. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43679. _this._renderTargets.push(_this._refractionTexture);
  43680. }
  43681. return _this._renderTargets;
  43682. };
  43683. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43684. return _this;
  43685. }
  43686. /**
  43687. * Attaches a new image processing configuration to the PBR Material.
  43688. * @param configuration
  43689. */
  43690. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43691. var _this = this;
  43692. if (configuration === this._imageProcessingConfiguration) {
  43693. return;
  43694. }
  43695. // Detaches observer.
  43696. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43697. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43698. }
  43699. // Pick the scene configuration if needed.
  43700. if (!configuration) {
  43701. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43702. }
  43703. else {
  43704. this._imageProcessingConfiguration = configuration;
  43705. }
  43706. // Attaches observer.
  43707. if (this._imageProcessingConfiguration) {
  43708. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43709. _this._markAllSubMeshesAsImageProcessingDirty();
  43710. });
  43711. }
  43712. };
  43713. /**
  43714. * Gets the name of the material class.
  43715. */
  43716. PBRBaseMaterial.prototype.getClassName = function () {
  43717. return "PBRBaseMaterial";
  43718. };
  43719. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43720. /**
  43721. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43722. */
  43723. get: function () {
  43724. return this._useLogarithmicDepth;
  43725. },
  43726. /**
  43727. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43728. */
  43729. set: function (value) {
  43730. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43731. },
  43732. enumerable: true,
  43733. configurable: true
  43734. });
  43735. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43736. /**
  43737. * Gets the current transparency mode.
  43738. */
  43739. get: function () {
  43740. return this._transparencyMode;
  43741. },
  43742. /**
  43743. * Sets the transparency mode of the material.
  43744. *
  43745. * | Value | Type | Description |
  43746. * | ----- | ----------------------------------- | ----------- |
  43747. * | 0 | OPAQUE | |
  43748. * | 1 | ALPHATEST | |
  43749. * | 2 | ALPHABLEND | |
  43750. * | 3 | ALPHATESTANDBLEND | |
  43751. *
  43752. */
  43753. set: function (value) {
  43754. if (this._transparencyMode === value) {
  43755. return;
  43756. }
  43757. this._transparencyMode = value;
  43758. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43759. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43760. },
  43761. enumerable: true,
  43762. configurable: true
  43763. });
  43764. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43765. /**
  43766. * Returns true if alpha blending should be disabled.
  43767. */
  43768. get: function () {
  43769. return (this._linkRefractionWithTransparency ||
  43770. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43771. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43772. },
  43773. enumerable: true,
  43774. configurable: true
  43775. });
  43776. /**
  43777. * Specifies whether or not this material should be rendered in alpha blend mode.
  43778. */
  43779. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43780. if (this._disableAlphaBlending) {
  43781. return false;
  43782. }
  43783. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43784. };
  43785. /**
  43786. * Specifies if the mesh will require alpha blending.
  43787. * @param mesh - BJS mesh.
  43788. */
  43789. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43790. if (this._disableAlphaBlending) {
  43791. return false;
  43792. }
  43793. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43794. };
  43795. /**
  43796. * Specifies whether or not this material should be rendered in alpha test mode.
  43797. */
  43798. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43799. if (this._forceAlphaTest) {
  43800. return true;
  43801. }
  43802. if (this._linkRefractionWithTransparency) {
  43803. return false;
  43804. }
  43805. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43806. };
  43807. /**
  43808. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43809. */
  43810. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43811. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43812. };
  43813. /**
  43814. * Gets the texture used for the alpha test.
  43815. */
  43816. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43817. return this._albedoTexture;
  43818. };
  43819. /**
  43820. * Specifies that the submesh is ready to be used.
  43821. * @param mesh - BJS mesh.
  43822. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43823. * @param useInstances - Specifies that instances should be used.
  43824. * @returns - boolean indicating that the submesh is ready or not.
  43825. */
  43826. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43827. if (subMesh.effect && this.isFrozen) {
  43828. if (this._wasPreviouslyReady) {
  43829. return true;
  43830. }
  43831. }
  43832. if (!subMesh._materialDefines) {
  43833. subMesh._materialDefines = new PBRMaterialDefines();
  43834. }
  43835. var defines = subMesh._materialDefines;
  43836. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43837. if (defines._renderId === this.getScene().getRenderId()) {
  43838. return true;
  43839. }
  43840. }
  43841. var scene = this.getScene();
  43842. var engine = scene.getEngine();
  43843. if (defines._areTexturesDirty) {
  43844. if (scene.texturesEnabled) {
  43845. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43846. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43847. return false;
  43848. }
  43849. }
  43850. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43851. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43852. return false;
  43853. }
  43854. }
  43855. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43856. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43857. return false;
  43858. }
  43859. }
  43860. var reflectionTexture = this._getReflectionTexture();
  43861. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43862. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43863. return false;
  43864. }
  43865. }
  43866. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43867. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43868. return false;
  43869. }
  43870. }
  43871. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43872. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43873. return false;
  43874. }
  43875. }
  43876. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43877. if (this._metallicTexture) {
  43878. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43879. return false;
  43880. }
  43881. }
  43882. else if (this._reflectivityTexture) {
  43883. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43884. return false;
  43885. }
  43886. }
  43887. if (this._microSurfaceTexture) {
  43888. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43889. return false;
  43890. }
  43891. }
  43892. }
  43893. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43894. // Bump texture cannot be not blocking.
  43895. if (!this._bumpTexture.isReady()) {
  43896. return false;
  43897. }
  43898. }
  43899. var refractionTexture = this._getRefractionTexture();
  43900. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43901. if (!refractionTexture.isReadyOrNotBlocking()) {
  43902. return false;
  43903. }
  43904. }
  43905. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43906. // This is blocking.
  43907. if (!this._environmentBRDFTexture.isReady()) {
  43908. return false;
  43909. }
  43910. }
  43911. }
  43912. }
  43913. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43914. if (!this._imageProcessingConfiguration.isReady()) {
  43915. return false;
  43916. }
  43917. }
  43918. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43919. mesh.createNormals(true);
  43920. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43921. }
  43922. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43923. if (effect) {
  43924. scene.resetCachedMaterial();
  43925. subMesh.setEffect(effect, defines);
  43926. this.buildUniformLayout();
  43927. }
  43928. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43929. return false;
  43930. }
  43931. defines._renderId = scene.getRenderId();
  43932. this._wasPreviouslyReady = true;
  43933. return true;
  43934. };
  43935. /**
  43936. * Specifies if the material uses metallic roughness workflow.
  43937. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43938. */
  43939. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43940. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43941. return true;
  43942. }
  43943. return false;
  43944. };
  43945. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43946. if (onCompiled === void 0) { onCompiled = null; }
  43947. if (onError === void 0) { onError = null; }
  43948. if (useInstances === void 0) { useInstances = null; }
  43949. if (useClipPlane === void 0) { useClipPlane = null; }
  43950. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43951. if (!defines.isDirty) {
  43952. return null;
  43953. }
  43954. defines.markAsProcessed();
  43955. var scene = this.getScene();
  43956. var engine = scene.getEngine();
  43957. // Fallbacks
  43958. var fallbacks = new BABYLON.EffectFallbacks();
  43959. var fallbackRank = 0;
  43960. if (defines.USESPHERICALINVERTEX) {
  43961. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43962. }
  43963. if (defines.FOG) {
  43964. fallbacks.addFallback(fallbackRank, "FOG");
  43965. }
  43966. if (defines.SPECULARAA) {
  43967. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43968. }
  43969. if (defines.POINTSIZE) {
  43970. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43971. }
  43972. if (defines.LOGARITHMICDEPTH) {
  43973. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43974. }
  43975. if (defines.PARALLAX) {
  43976. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43977. }
  43978. if (defines.PARALLAXOCCLUSION) {
  43979. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43980. }
  43981. if (defines.ENVIRONMENTBRDF) {
  43982. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43983. }
  43984. if (defines.TANGENT) {
  43985. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43986. }
  43987. if (defines.BUMP) {
  43988. fallbacks.addFallback(fallbackRank++, "BUMP");
  43989. }
  43990. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43991. if (defines.SPECULARTERM) {
  43992. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43993. }
  43994. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43995. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43996. }
  43997. if (defines.LIGHTMAP) {
  43998. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43999. }
  44000. if (defines.NORMAL) {
  44001. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44002. }
  44003. if (defines.AMBIENT) {
  44004. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44005. }
  44006. if (defines.EMISSIVE) {
  44007. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44008. }
  44009. if (defines.VERTEXCOLOR) {
  44010. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44011. }
  44012. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44013. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44014. }
  44015. if (defines.MORPHTARGETS) {
  44016. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44017. }
  44018. //Attributes
  44019. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44020. if (defines.NORMAL) {
  44021. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44022. }
  44023. if (defines.TANGENT) {
  44024. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44025. }
  44026. if (defines.UV1) {
  44027. attribs.push(BABYLON.VertexBuffer.UVKind);
  44028. }
  44029. if (defines.UV2) {
  44030. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44031. }
  44032. if (defines.VERTEXCOLOR) {
  44033. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44034. }
  44035. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44036. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44037. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44038. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44039. "vFogInfos", "vFogColor", "pointSize",
  44040. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44041. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44042. "mBones",
  44043. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44044. "vLightingIntensity",
  44045. "logarithmicDepthConstant",
  44046. "vSphericalX", "vSphericalY", "vSphericalZ",
  44047. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44048. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44049. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44050. "vTangentSpaceParams"
  44051. ];
  44052. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44053. "bumpSampler", "lightmapSampler", "opacitySampler",
  44054. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44055. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44056. "microSurfaceSampler", "environmentBrdfSampler"];
  44057. var uniformBuffers = ["Material", "Scene"];
  44058. if (BABYLON.ImageProcessingConfiguration) {
  44059. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44060. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44061. }
  44062. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44063. uniformsNames: uniforms,
  44064. uniformBuffersNames: uniformBuffers,
  44065. samplers: samplers,
  44066. defines: defines,
  44067. maxSimultaneousLights: this._maxSimultaneousLights
  44068. });
  44069. var join = defines.toString();
  44070. return engine.createEffect("pbr", {
  44071. attributes: attribs,
  44072. uniformsNames: uniforms,
  44073. uniformBuffersNames: uniformBuffers,
  44074. samplers: samplers,
  44075. defines: join,
  44076. fallbacks: fallbacks,
  44077. onCompiled: onCompiled,
  44078. onError: onError,
  44079. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44080. }, engine);
  44081. };
  44082. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44083. if (useInstances === void 0) { useInstances = null; }
  44084. if (useClipPlane === void 0) { useClipPlane = null; }
  44085. var scene = this.getScene();
  44086. var engine = scene.getEngine();
  44087. // Lights
  44088. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44089. defines._needNormals = true;
  44090. // Textures
  44091. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44092. if (defines._areTexturesDirty) {
  44093. defines._needUVs = false;
  44094. if (scene.texturesEnabled) {
  44095. if (scene.getEngine().getCaps().textureLOD) {
  44096. defines.LODBASEDMICROSFURACE = true;
  44097. }
  44098. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44099. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44100. }
  44101. else {
  44102. defines.ALBEDO = false;
  44103. }
  44104. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44105. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44106. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44107. }
  44108. else {
  44109. defines.AMBIENT = false;
  44110. }
  44111. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44113. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44114. }
  44115. else {
  44116. defines.OPACITY = false;
  44117. }
  44118. var reflectionTexture = this._getReflectionTexture();
  44119. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44120. defines.REFLECTION = true;
  44121. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44122. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44123. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44124. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44125. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44126. defines.INVERTCUBICMAP = true;
  44127. }
  44128. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44129. switch (reflectionTexture.coordinatesMode) {
  44130. case BABYLON.Texture.EXPLICIT_MODE:
  44131. defines.REFLECTIONMAP_EXPLICIT = true;
  44132. break;
  44133. case BABYLON.Texture.PLANAR_MODE:
  44134. defines.REFLECTIONMAP_PLANAR = true;
  44135. break;
  44136. case BABYLON.Texture.PROJECTION_MODE:
  44137. defines.REFLECTIONMAP_PROJECTION = true;
  44138. break;
  44139. case BABYLON.Texture.SKYBOX_MODE:
  44140. defines.REFLECTIONMAP_SKYBOX = true;
  44141. break;
  44142. case BABYLON.Texture.SPHERICAL_MODE:
  44143. defines.REFLECTIONMAP_SPHERICAL = true;
  44144. break;
  44145. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44146. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44147. break;
  44148. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44149. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44150. break;
  44151. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44152. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44153. break;
  44154. case BABYLON.Texture.CUBIC_MODE:
  44155. case BABYLON.Texture.INVCUBIC_MODE:
  44156. default:
  44157. defines.REFLECTIONMAP_CUBIC = true;
  44158. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44159. break;
  44160. }
  44161. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44162. if (reflectionTexture.sphericalPolynomial) {
  44163. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44164. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44165. defines.USESPHERICALINVERTEX = false;
  44166. }
  44167. else {
  44168. defines.USESPHERICALINVERTEX = true;
  44169. }
  44170. }
  44171. }
  44172. }
  44173. else {
  44174. defines.REFLECTION = false;
  44175. defines.REFLECTIONMAP_3D = false;
  44176. defines.REFLECTIONMAP_SPHERICAL = false;
  44177. defines.REFLECTIONMAP_PLANAR = false;
  44178. defines.REFLECTIONMAP_CUBIC = false;
  44179. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44180. defines.REFLECTIONMAP_PROJECTION = false;
  44181. defines.REFLECTIONMAP_SKYBOX = false;
  44182. defines.REFLECTIONMAP_EXPLICIT = false;
  44183. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44184. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44185. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44186. defines.INVERTCUBICMAP = false;
  44187. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44188. defines.USESPHERICALINVERTEX = false;
  44189. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44190. defines.LODINREFLECTIONALPHA = false;
  44191. defines.GAMMAREFLECTION = false;
  44192. defines.RGBDREFLECTION = false;
  44193. }
  44194. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44195. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44196. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44197. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44198. }
  44199. else {
  44200. defines.LIGHTMAP = false;
  44201. }
  44202. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44203. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44204. }
  44205. else {
  44206. defines.EMISSIVE = false;
  44207. }
  44208. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44209. if (this._metallicTexture) {
  44210. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44211. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44212. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44213. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44214. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44215. }
  44216. else if (this._reflectivityTexture) {
  44217. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44218. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44219. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44220. }
  44221. else {
  44222. defines.REFLECTIVITY = false;
  44223. }
  44224. if (this._microSurfaceTexture) {
  44225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44226. }
  44227. else {
  44228. defines.MICROSURFACEMAP = false;
  44229. }
  44230. }
  44231. else {
  44232. defines.REFLECTIVITY = false;
  44233. defines.MICROSURFACEMAP = false;
  44234. }
  44235. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44236. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44237. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44238. defines.PARALLAX = true;
  44239. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44240. }
  44241. else {
  44242. defines.PARALLAX = false;
  44243. }
  44244. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44245. }
  44246. else {
  44247. defines.BUMP = false;
  44248. }
  44249. var refractionTexture = this._getRefractionTexture();
  44250. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44251. defines.REFRACTION = true;
  44252. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44253. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44254. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44255. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44256. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44257. if (this._linkRefractionWithTransparency) {
  44258. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44259. }
  44260. }
  44261. else {
  44262. defines.REFRACTION = false;
  44263. }
  44264. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44265. defines.ENVIRONMENTBRDF = true;
  44266. }
  44267. else {
  44268. defines.ENVIRONMENTBRDF = false;
  44269. }
  44270. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44271. defines.ALPHAFROMALBEDO = true;
  44272. }
  44273. else {
  44274. defines.ALPHAFROMALBEDO = false;
  44275. }
  44276. }
  44277. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44278. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44279. defines.USEPHYSICALLIGHTFALLOFF = false;
  44280. defines.USEGLTFLIGHTFALLOFF = false;
  44281. }
  44282. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44283. defines.USEPHYSICALLIGHTFALLOFF = false;
  44284. defines.USEGLTFLIGHTFALLOFF = true;
  44285. }
  44286. else {
  44287. defines.USEPHYSICALLIGHTFALLOFF = true;
  44288. defines.USEGLTFLIGHTFALLOFF = false;
  44289. }
  44290. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44291. if (!this.backFaceCulling && this._twoSidedLighting) {
  44292. defines.TWOSIDEDLIGHTING = true;
  44293. }
  44294. else {
  44295. defines.TWOSIDEDLIGHTING = false;
  44296. }
  44297. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44298. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44299. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44300. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44301. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44302. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44303. }
  44304. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44305. this._imageProcessingConfiguration.prepareDefines(defines);
  44306. }
  44307. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44308. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44309. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44310. // Misc.
  44311. if (defines._areMiscDirty) {
  44312. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44313. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44314. }
  44315. // Values that need to be evaluated on every frame
  44316. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44317. // Attribs
  44318. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44319. };
  44320. /**
  44321. * Force shader compilation
  44322. */
  44323. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44324. var _this = this;
  44325. var localOptions = __assign({ clipPlane: false }, options);
  44326. var defines = new PBRMaterialDefines();
  44327. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44328. if (effect.isReady()) {
  44329. if (onCompiled) {
  44330. onCompiled(this);
  44331. }
  44332. }
  44333. else {
  44334. effect.onCompileObservable.add(function () {
  44335. if (onCompiled) {
  44336. onCompiled(_this);
  44337. }
  44338. });
  44339. }
  44340. };
  44341. /**
  44342. * Initializes the uniform buffer layout for the shader.
  44343. */
  44344. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44345. // Order is important !
  44346. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44347. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44348. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44349. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44350. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44351. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44352. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44353. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44354. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44355. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44356. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44357. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44358. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44359. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44360. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44361. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44362. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44363. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44364. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44365. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44366. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44367. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44368. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44369. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44370. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44371. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44372. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44373. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44374. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44375. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44376. this._uniformBuffer.addUniform("pointSize", 1);
  44377. this._uniformBuffer.create();
  44378. };
  44379. /**
  44380. * Unbinds the textures.
  44381. */
  44382. PBRBaseMaterial.prototype.unbind = function () {
  44383. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44384. this._uniformBuffer.setTexture("reflectionSampler", null);
  44385. }
  44386. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44387. this._uniformBuffer.setTexture("refractionSampler", null);
  44388. }
  44389. _super.prototype.unbind.call(this);
  44390. };
  44391. /**
  44392. * Binds the submesh data.
  44393. * @param world - The world matrix.
  44394. * @param mesh - The BJS mesh.
  44395. * @param subMesh - A submesh of the BJS mesh.
  44396. */
  44397. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44398. var scene = this.getScene();
  44399. var defines = subMesh._materialDefines;
  44400. if (!defines) {
  44401. return;
  44402. }
  44403. var effect = subMesh.effect;
  44404. if (!effect) {
  44405. return;
  44406. }
  44407. this._activeEffect = effect;
  44408. // Matrices
  44409. this.bindOnlyWorldMatrix(world);
  44410. // Normal Matrix
  44411. if (defines.OBJECTSPACE_NORMALMAP) {
  44412. world.toNormalMatrix(this._normalMatrix);
  44413. this.bindOnlyNormalMatrix(this._normalMatrix);
  44414. }
  44415. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44416. // Bones
  44417. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44418. var reflectionTexture = null;
  44419. if (mustRebind) {
  44420. this._uniformBuffer.bindToEffect(effect, "Material");
  44421. this.bindViewProjection(effect);
  44422. reflectionTexture = this._getReflectionTexture();
  44423. var refractionTexture = this._getRefractionTexture();
  44424. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44425. // Texture uniforms
  44426. if (scene.texturesEnabled) {
  44427. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44428. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44429. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44430. }
  44431. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44432. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44433. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44434. }
  44435. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44436. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44437. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44438. }
  44439. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44440. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44441. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44442. if (reflectionTexture.boundingBoxSize) {
  44443. var cubeTexture = reflectionTexture;
  44444. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44445. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44446. }
  44447. var polynomials = reflectionTexture.sphericalPolynomial;
  44448. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44449. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44450. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44451. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44452. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44453. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44454. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44455. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44456. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44457. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44458. }
  44459. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44460. }
  44461. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44462. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44463. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44464. }
  44465. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44466. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44467. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44468. }
  44469. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44470. if (this._metallicTexture) {
  44471. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44472. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44473. }
  44474. else if (this._reflectivityTexture) {
  44475. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44476. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44477. }
  44478. if (this._microSurfaceTexture) {
  44479. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44480. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44481. }
  44482. }
  44483. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44484. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44485. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44486. if (scene._mirroredCameraPosition) {
  44487. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44488. }
  44489. else {
  44490. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44491. }
  44492. }
  44493. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44494. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44495. var depth = 1.0;
  44496. if (!refractionTexture.isCube) {
  44497. if (refractionTexture.depth) {
  44498. depth = refractionTexture.depth;
  44499. }
  44500. }
  44501. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44502. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44503. }
  44504. }
  44505. // Point size
  44506. if (this.pointsCloud) {
  44507. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44508. }
  44509. // Colors
  44510. if (defines.METALLICWORKFLOW) {
  44511. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44512. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44513. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44514. }
  44515. else {
  44516. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44517. }
  44518. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44519. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44520. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44521. // Misc
  44522. this._lightingInfos.x = this._directIntensity;
  44523. this._lightingInfos.y = this._emissiveIntensity;
  44524. this._lightingInfos.z = this._environmentIntensity;
  44525. this._lightingInfos.w = this._specularIntensity;
  44526. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44527. }
  44528. // Textures
  44529. if (scene.texturesEnabled) {
  44530. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44531. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44532. }
  44533. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44534. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44535. }
  44536. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44537. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44538. }
  44539. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44540. if (defines.LODBASEDMICROSFURACE) {
  44541. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44542. }
  44543. else {
  44544. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44545. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44546. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44547. }
  44548. }
  44549. if (defines.ENVIRONMENTBRDF) {
  44550. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44551. }
  44552. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44553. if (defines.LODBASEDMICROSFURACE) {
  44554. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44555. }
  44556. else {
  44557. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44558. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44559. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44560. }
  44561. }
  44562. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44563. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44564. }
  44565. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44566. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44567. }
  44568. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44569. if (this._metallicTexture) {
  44570. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44571. }
  44572. else if (this._reflectivityTexture) {
  44573. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44574. }
  44575. if (this._microSurfaceTexture) {
  44576. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44577. }
  44578. }
  44579. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44580. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44581. }
  44582. }
  44583. // Clip plane
  44584. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44585. // Colors
  44586. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44587. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44588. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44589. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44590. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44591. }
  44592. if (mustRebind || !this.isFrozen) {
  44593. // Lights
  44594. if (scene.lightsEnabled && !this._disableLighting) {
  44595. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44596. }
  44597. // View
  44598. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44599. this.bindView(effect);
  44600. }
  44601. // Fog
  44602. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44603. // Morph targets
  44604. if (defines.NUM_MORPH_INFLUENCERS) {
  44605. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44606. }
  44607. // image processing
  44608. this._imageProcessingConfiguration.bind(this._activeEffect);
  44609. // Log. depth
  44610. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44611. }
  44612. this._uniformBuffer.update();
  44613. this._afterBind(mesh, this._activeEffect);
  44614. };
  44615. /**
  44616. * Returns the animatable textures.
  44617. * @returns - Array of animatable textures.
  44618. */
  44619. PBRBaseMaterial.prototype.getAnimatables = function () {
  44620. var results = [];
  44621. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44622. results.push(this._albedoTexture);
  44623. }
  44624. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44625. results.push(this._ambientTexture);
  44626. }
  44627. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44628. results.push(this._opacityTexture);
  44629. }
  44630. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44631. results.push(this._reflectionTexture);
  44632. }
  44633. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44634. results.push(this._emissiveTexture);
  44635. }
  44636. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44637. results.push(this._metallicTexture);
  44638. }
  44639. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44640. results.push(this._reflectivityTexture);
  44641. }
  44642. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44643. results.push(this._bumpTexture);
  44644. }
  44645. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44646. results.push(this._lightmapTexture);
  44647. }
  44648. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44649. results.push(this._refractionTexture);
  44650. }
  44651. return results;
  44652. };
  44653. /**
  44654. * Returns the texture used for reflections.
  44655. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44656. */
  44657. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44658. if (this._reflectionTexture) {
  44659. return this._reflectionTexture;
  44660. }
  44661. return this.getScene().environmentTexture;
  44662. };
  44663. /**
  44664. * Returns the texture used for refraction or null if none is used.
  44665. * @returns - Refection texture if present. If no refraction texture and refraction
  44666. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44667. */
  44668. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44669. if (this._refractionTexture) {
  44670. return this._refractionTexture;
  44671. }
  44672. if (this._linkRefractionWithTransparency) {
  44673. return this.getScene().environmentTexture;
  44674. }
  44675. return null;
  44676. };
  44677. /**
  44678. * Disposes the resources of the material.
  44679. * @param forceDisposeEffect - Forces the disposal of effects.
  44680. * @param forceDisposeTextures - Forces the disposal of all textures.
  44681. */
  44682. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44683. if (forceDisposeTextures) {
  44684. if (this._albedoTexture) {
  44685. this._albedoTexture.dispose();
  44686. }
  44687. if (this._ambientTexture) {
  44688. this._ambientTexture.dispose();
  44689. }
  44690. if (this._opacityTexture) {
  44691. this._opacityTexture.dispose();
  44692. }
  44693. if (this._reflectionTexture) {
  44694. this._reflectionTexture.dispose();
  44695. }
  44696. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44697. this._environmentBRDFTexture.dispose();
  44698. }
  44699. if (this._emissiveTexture) {
  44700. this._emissiveTexture.dispose();
  44701. }
  44702. if (this._metallicTexture) {
  44703. this._metallicTexture.dispose();
  44704. }
  44705. if (this._reflectivityTexture) {
  44706. this._reflectivityTexture.dispose();
  44707. }
  44708. if (this._bumpTexture) {
  44709. this._bumpTexture.dispose();
  44710. }
  44711. if (this._lightmapTexture) {
  44712. this._lightmapTexture.dispose();
  44713. }
  44714. if (this._refractionTexture) {
  44715. this._refractionTexture.dispose();
  44716. }
  44717. }
  44718. this._renderTargets.dispose();
  44719. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44720. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44721. }
  44722. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44723. };
  44724. /**
  44725. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44726. */
  44727. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44728. /**
  44729. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44730. * to enhance interoperability with other engines.
  44731. */
  44732. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44733. /**
  44734. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44735. * to enhance interoperability with other materials.
  44736. */
  44737. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44738. /**
  44739. * Stores the reflectivity values based on metallic roughness workflow.
  44740. */
  44741. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44742. __decorate([
  44743. BABYLON.serializeAsImageProcessingConfiguration()
  44744. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44745. __decorate([
  44746. BABYLON.serialize()
  44747. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44748. __decorate([
  44749. BABYLON.serialize()
  44750. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44751. return PBRBaseMaterial;
  44752. }(BABYLON.PushMaterial));
  44753. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44754. })(BABYLON || (BABYLON = {}));
  44755. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44756. var BABYLON;
  44757. (function (BABYLON) {
  44758. /**
  44759. * The Physically based simple base material of BJS.
  44760. *
  44761. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44762. * It is used as the base class for both the specGloss and metalRough conventions.
  44763. */
  44764. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44765. __extends(PBRBaseSimpleMaterial, _super);
  44766. /**
  44767. * Instantiates a new PBRMaterial instance.
  44768. *
  44769. * @param name The material name
  44770. * @param scene The scene the material will be use in.
  44771. */
  44772. function PBRBaseSimpleMaterial(name, scene) {
  44773. var _this = _super.call(this, name, scene) || this;
  44774. /**
  44775. * Number of Simultaneous lights allowed on the material.
  44776. */
  44777. _this.maxSimultaneousLights = 4;
  44778. /**
  44779. * If sets to true, disables all the lights affecting the material.
  44780. */
  44781. _this.disableLighting = false;
  44782. /**
  44783. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44784. */
  44785. _this.invertNormalMapX = false;
  44786. /**
  44787. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44788. */
  44789. _this.invertNormalMapY = false;
  44790. /**
  44791. * Emissivie color used to self-illuminate the model.
  44792. */
  44793. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44794. /**
  44795. * Occlusion Channel Strenght.
  44796. */
  44797. _this.occlusionStrength = 1.0;
  44798. _this.useLightmapAsShadowmap = false;
  44799. _this._useAlphaFromAlbedoTexture = true;
  44800. _this._useAmbientInGrayScale = true;
  44801. return _this;
  44802. }
  44803. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44804. /**
  44805. * Gets the current double sided mode.
  44806. */
  44807. get: function () {
  44808. return this._twoSidedLighting;
  44809. },
  44810. /**
  44811. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44812. */
  44813. set: function (value) {
  44814. if (this._twoSidedLighting === value) {
  44815. return;
  44816. }
  44817. this._twoSidedLighting = value;
  44818. this.backFaceCulling = !value;
  44819. this._markAllSubMeshesAsTexturesDirty();
  44820. },
  44821. enumerable: true,
  44822. configurable: true
  44823. });
  44824. /**
  44825. * Return the active textures of the material.
  44826. */
  44827. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44828. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44829. if (this.environmentTexture) {
  44830. activeTextures.push(this.environmentTexture);
  44831. }
  44832. if (this.normalTexture) {
  44833. activeTextures.push(this.normalTexture);
  44834. }
  44835. if (this.emissiveTexture) {
  44836. activeTextures.push(this.emissiveTexture);
  44837. }
  44838. if (this.occlusionTexture) {
  44839. activeTextures.push(this.occlusionTexture);
  44840. }
  44841. if (this.lightmapTexture) {
  44842. activeTextures.push(this.lightmapTexture);
  44843. }
  44844. return activeTextures;
  44845. };
  44846. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44847. if (_super.prototype.hasTexture.call(this, texture)) {
  44848. return true;
  44849. }
  44850. if (this.lightmapTexture === texture) {
  44851. return true;
  44852. }
  44853. return false;
  44854. };
  44855. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44856. return "PBRBaseSimpleMaterial";
  44857. };
  44858. __decorate([
  44859. BABYLON.serialize(),
  44860. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44861. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44862. __decorate([
  44863. BABYLON.serialize(),
  44864. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44865. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44866. __decorate([
  44867. BABYLON.serializeAsTexture(),
  44868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44869. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44870. __decorate([
  44871. BABYLON.serialize(),
  44872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44873. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44874. __decorate([
  44875. BABYLON.serialize(),
  44876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44877. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44878. __decorate([
  44879. BABYLON.serializeAsTexture(),
  44880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44881. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44882. __decorate([
  44883. BABYLON.serializeAsColor3("emissive"),
  44884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44885. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44886. __decorate([
  44887. BABYLON.serializeAsTexture(),
  44888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44889. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44890. __decorate([
  44891. BABYLON.serialize(),
  44892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44893. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44894. __decorate([
  44895. BABYLON.serializeAsTexture(),
  44896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44897. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44898. __decorate([
  44899. BABYLON.serialize(),
  44900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44901. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44902. __decorate([
  44903. BABYLON.serialize()
  44904. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44905. __decorate([
  44906. BABYLON.serializeAsTexture(),
  44907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44908. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44909. __decorate([
  44910. BABYLON.serialize(),
  44911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44912. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44913. return PBRBaseSimpleMaterial;
  44914. }(BABYLON.PBRBaseMaterial));
  44915. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44916. })(BABYLON || (BABYLON = {}));
  44917. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44918. var BABYLON;
  44919. (function (BABYLON) {
  44920. /**
  44921. * The Physically based material of BJS.
  44922. *
  44923. * This offers the main features of a standard PBR material.
  44924. * For more information, please refer to the documentation :
  44925. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44926. */
  44927. var PBRMaterial = /** @class */ (function (_super) {
  44928. __extends(PBRMaterial, _super);
  44929. /**
  44930. * Instantiates a new PBRMaterial instance.
  44931. *
  44932. * @param name The material name
  44933. * @param scene The scene the material will be use in.
  44934. */
  44935. function PBRMaterial(name, scene) {
  44936. var _this = _super.call(this, name, scene) || this;
  44937. /**
  44938. * Intensity of the direct lights e.g. the four lights available in your scene.
  44939. * This impacts both the direct diffuse and specular highlights.
  44940. */
  44941. _this.directIntensity = 1.0;
  44942. /**
  44943. * Intensity of the emissive part of the material.
  44944. * This helps controlling the emissive effect without modifying the emissive color.
  44945. */
  44946. _this.emissiveIntensity = 1.0;
  44947. /**
  44948. * Intensity of the environment e.g. how much the environment will light the object
  44949. * either through harmonics for rough material or through the refelction for shiny ones.
  44950. */
  44951. _this.environmentIntensity = 1.0;
  44952. /**
  44953. * This is a special control allowing the reduction of the specular highlights coming from the
  44954. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44955. */
  44956. _this.specularIntensity = 1.0;
  44957. /**
  44958. * Debug Control allowing disabling the bump map on this material.
  44959. */
  44960. _this.disableBumpMap = false;
  44961. /**
  44962. * AKA Occlusion Texture Intensity in other nomenclature.
  44963. */
  44964. _this.ambientTextureStrength = 1.0;
  44965. /**
  44966. * The color of a material in ambient lighting.
  44967. */
  44968. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44969. /**
  44970. * AKA Diffuse Color in other nomenclature.
  44971. */
  44972. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44973. /**
  44974. * AKA Specular Color in other nomenclature.
  44975. */
  44976. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44977. /**
  44978. * The color reflected from the material.
  44979. */
  44980. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44981. /**
  44982. * The color emitted from the material.
  44983. */
  44984. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44985. /**
  44986. * AKA Glossiness in other nomenclature.
  44987. */
  44988. _this.microSurface = 1.0;
  44989. /**
  44990. * source material index of refraction (IOR)' / 'destination material IOR.
  44991. */
  44992. _this.indexOfRefraction = 0.66;
  44993. /**
  44994. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44995. */
  44996. _this.invertRefractionY = false;
  44997. /**
  44998. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44999. * Materials half opaque for instance using refraction could benefit from this control.
  45000. */
  45001. _this.linkRefractionWithTransparency = false;
  45002. _this.useLightmapAsShadowmap = false;
  45003. /**
  45004. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45005. */
  45006. _this.useAlphaFromAlbedoTexture = false;
  45007. /**
  45008. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45009. */
  45010. _this.forceAlphaTest = false;
  45011. /**
  45012. * Defines the alpha limits in alpha test mode.
  45013. */
  45014. _this.alphaCutOff = 0.4;
  45015. /**
  45016. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45017. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45018. */
  45019. _this.useSpecularOverAlpha = true;
  45020. /**
  45021. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45022. */
  45023. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45024. /**
  45025. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45026. */
  45027. _this.useRoughnessFromMetallicTextureAlpha = true;
  45028. /**
  45029. * Specifies if the metallic texture contains the roughness information in its green channel.
  45030. */
  45031. _this.useRoughnessFromMetallicTextureGreen = false;
  45032. /**
  45033. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45034. */
  45035. _this.useMetallnessFromMetallicTextureBlue = false;
  45036. /**
  45037. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45038. */
  45039. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45040. /**
  45041. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45042. */
  45043. _this.useAmbientInGrayScale = false;
  45044. /**
  45045. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45046. * The material will try to infer what glossiness each pixel should be.
  45047. */
  45048. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45049. /**
  45050. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45051. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45052. */
  45053. _this.useRadianceOverAlpha = true;
  45054. /**
  45055. * Allows using an object space normal map (instead of tangent space).
  45056. */
  45057. _this.useObjectSpaceNormalMap = false;
  45058. /**
  45059. * Allows using the bump map in parallax mode.
  45060. */
  45061. _this.useParallax = false;
  45062. /**
  45063. * Allows using the bump map in parallax occlusion mode.
  45064. */
  45065. _this.useParallaxOcclusion = false;
  45066. /**
  45067. * Controls the scale bias of the parallax mode.
  45068. */
  45069. _this.parallaxScaleBias = 0.05;
  45070. /**
  45071. * If sets to true, disables all the lights affecting the material.
  45072. */
  45073. _this.disableLighting = false;
  45074. /**
  45075. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45076. */
  45077. _this.forceIrradianceInFragment = false;
  45078. /**
  45079. * Number of Simultaneous lights allowed on the material.
  45080. */
  45081. _this.maxSimultaneousLights = 4;
  45082. /**
  45083. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45084. */
  45085. _this.invertNormalMapX = false;
  45086. /**
  45087. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45088. */
  45089. _this.invertNormalMapY = false;
  45090. /**
  45091. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45092. */
  45093. _this.twoSidedLighting = false;
  45094. /**
  45095. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45096. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45097. */
  45098. _this.useAlphaFresnel = false;
  45099. /**
  45100. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45101. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45102. */
  45103. _this.useLinearAlphaFresnel = false;
  45104. /**
  45105. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45106. * And/Or occlude the blended part.
  45107. */
  45108. _this.environmentBRDFTexture = null;
  45109. /**
  45110. * Force normal to face away from face.
  45111. */
  45112. _this.forceNormalForward = false;
  45113. /**
  45114. * Enables specular anti aliasing in the PBR shader.
  45115. * It will both interacts on the Geometry for analytical and IBL lighting.
  45116. * It also prefilter the roughness map based on the bump values.
  45117. */
  45118. _this.enableSpecularAntiAliasing = false;
  45119. /**
  45120. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45121. * makes the reflect vector face the model (under horizon).
  45122. */
  45123. _this.useHorizonOcclusion = true;
  45124. /**
  45125. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45126. * too much the area relying on ambient texture to define their ambient occlusion.
  45127. */
  45128. _this.useRadianceOcclusion = true;
  45129. /**
  45130. * If set to true, no lighting calculations will be applied.
  45131. */
  45132. _this.unlit = false;
  45133. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45134. return _this;
  45135. }
  45136. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45137. /**
  45138. * BJS is using an harcoded light falloff based on a manually sets up range.
  45139. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45140. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45141. */
  45142. get: function () {
  45143. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45144. },
  45145. /**
  45146. * BJS is using an harcoded light falloff based on a manually sets up range.
  45147. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45148. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45149. */
  45150. set: function (value) {
  45151. if (value !== this.usePhysicalLightFalloff) {
  45152. // Ensure the effect will be rebuilt.
  45153. this._markAllSubMeshesAsTexturesDirty();
  45154. if (value) {
  45155. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45156. }
  45157. else {
  45158. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45159. }
  45160. }
  45161. },
  45162. enumerable: true,
  45163. configurable: true
  45164. });
  45165. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45166. /**
  45167. * In order to support the falloff compatibility with gltf, a special mode has been added
  45168. * to reproduce the gltf light falloff.
  45169. */
  45170. get: function () {
  45171. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45172. },
  45173. /**
  45174. * In order to support the falloff compatibility with gltf, a special mode has been added
  45175. * to reproduce the gltf light falloff.
  45176. */
  45177. set: function (value) {
  45178. if (value !== this.useGLTFLightFalloff) {
  45179. // Ensure the effect will be rebuilt.
  45180. this._markAllSubMeshesAsTexturesDirty();
  45181. if (value) {
  45182. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45183. }
  45184. else {
  45185. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45186. }
  45187. }
  45188. },
  45189. enumerable: true,
  45190. configurable: true
  45191. });
  45192. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45193. /**
  45194. * Gets the image processing configuration used either in this material.
  45195. */
  45196. get: function () {
  45197. return this._imageProcessingConfiguration;
  45198. },
  45199. /**
  45200. * Sets the Default image processing configuration used either in the this material.
  45201. *
  45202. * If sets to null, the scene one is in use.
  45203. */
  45204. set: function (value) {
  45205. this._attachImageProcessingConfiguration(value);
  45206. // Ensure the effect will be rebuilt.
  45207. this._markAllSubMeshesAsTexturesDirty();
  45208. },
  45209. enumerable: true,
  45210. configurable: true
  45211. });
  45212. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45213. /**
  45214. * Gets wether the color curves effect is enabled.
  45215. */
  45216. get: function () {
  45217. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45218. },
  45219. /**
  45220. * Sets wether the color curves effect is enabled.
  45221. */
  45222. set: function (value) {
  45223. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45224. },
  45225. enumerable: true,
  45226. configurable: true
  45227. });
  45228. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45229. /**
  45230. * Gets wether the color grading effect is enabled.
  45231. */
  45232. get: function () {
  45233. return this.imageProcessingConfiguration.colorGradingEnabled;
  45234. },
  45235. /**
  45236. * Gets wether the color grading effect is enabled.
  45237. */
  45238. set: function (value) {
  45239. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45240. },
  45241. enumerable: true,
  45242. configurable: true
  45243. });
  45244. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45245. /**
  45246. * Gets wether tonemapping is enabled or not.
  45247. */
  45248. get: function () {
  45249. return this._imageProcessingConfiguration.toneMappingEnabled;
  45250. },
  45251. /**
  45252. * Sets wether tonemapping is enabled or not
  45253. */
  45254. set: function (value) {
  45255. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45256. },
  45257. enumerable: true,
  45258. configurable: true
  45259. });
  45260. ;
  45261. ;
  45262. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45263. /**
  45264. * The camera exposure used on this material.
  45265. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45266. * This corresponds to a photographic exposure.
  45267. */
  45268. get: function () {
  45269. return this._imageProcessingConfiguration.exposure;
  45270. },
  45271. /**
  45272. * The camera exposure used on this material.
  45273. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45274. * This corresponds to a photographic exposure.
  45275. */
  45276. set: function (value) {
  45277. this._imageProcessingConfiguration.exposure = value;
  45278. },
  45279. enumerable: true,
  45280. configurable: true
  45281. });
  45282. ;
  45283. ;
  45284. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45285. /**
  45286. * Gets The camera contrast used on this material.
  45287. */
  45288. get: function () {
  45289. return this._imageProcessingConfiguration.contrast;
  45290. },
  45291. /**
  45292. * Sets The camera contrast used on this material.
  45293. */
  45294. set: function (value) {
  45295. this._imageProcessingConfiguration.contrast = value;
  45296. },
  45297. enumerable: true,
  45298. configurable: true
  45299. });
  45300. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45301. /**
  45302. * Gets the Color Grading 2D Lookup Texture.
  45303. */
  45304. get: function () {
  45305. return this._imageProcessingConfiguration.colorGradingTexture;
  45306. },
  45307. /**
  45308. * Sets the Color Grading 2D Lookup Texture.
  45309. */
  45310. set: function (value) {
  45311. this._imageProcessingConfiguration.colorGradingTexture = value;
  45312. },
  45313. enumerable: true,
  45314. configurable: true
  45315. });
  45316. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45317. /**
  45318. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45319. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45320. * 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;
  45321. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45322. */
  45323. get: function () {
  45324. return this._imageProcessingConfiguration.colorCurves;
  45325. },
  45326. /**
  45327. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45328. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45329. * 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;
  45330. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45331. */
  45332. set: function (value) {
  45333. this._imageProcessingConfiguration.colorCurves = value;
  45334. },
  45335. enumerable: true,
  45336. configurable: true
  45337. });
  45338. /**
  45339. * Returns the name of this material class.
  45340. */
  45341. PBRMaterial.prototype.getClassName = function () {
  45342. return "PBRMaterial";
  45343. };
  45344. /**
  45345. * Returns an array of the actively used textures.
  45346. * @returns - Array of BaseTextures
  45347. */
  45348. PBRMaterial.prototype.getActiveTextures = function () {
  45349. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45350. if (this._albedoTexture) {
  45351. activeTextures.push(this._albedoTexture);
  45352. }
  45353. if (this._ambientTexture) {
  45354. activeTextures.push(this._ambientTexture);
  45355. }
  45356. if (this._opacityTexture) {
  45357. activeTextures.push(this._opacityTexture);
  45358. }
  45359. if (this._reflectionTexture) {
  45360. activeTextures.push(this._reflectionTexture);
  45361. }
  45362. if (this._emissiveTexture) {
  45363. activeTextures.push(this._emissiveTexture);
  45364. }
  45365. if (this._reflectivityTexture) {
  45366. activeTextures.push(this._reflectivityTexture);
  45367. }
  45368. if (this._metallicTexture) {
  45369. activeTextures.push(this._metallicTexture);
  45370. }
  45371. if (this._microSurfaceTexture) {
  45372. activeTextures.push(this._microSurfaceTexture);
  45373. }
  45374. if (this._bumpTexture) {
  45375. activeTextures.push(this._bumpTexture);
  45376. }
  45377. if (this._lightmapTexture) {
  45378. activeTextures.push(this._lightmapTexture);
  45379. }
  45380. if (this._refractionTexture) {
  45381. activeTextures.push(this._refractionTexture);
  45382. }
  45383. return activeTextures;
  45384. };
  45385. /**
  45386. * Checks to see if a texture is used in the material.
  45387. * @param texture - Base texture to use.
  45388. * @returns - Boolean specifying if a texture is used in the material.
  45389. */
  45390. PBRMaterial.prototype.hasTexture = function (texture) {
  45391. if (_super.prototype.hasTexture.call(this, texture)) {
  45392. return true;
  45393. }
  45394. if (this._albedoTexture === texture) {
  45395. return true;
  45396. }
  45397. if (this._ambientTexture === texture) {
  45398. return true;
  45399. }
  45400. if (this._opacityTexture === texture) {
  45401. return true;
  45402. }
  45403. if (this._reflectionTexture === texture) {
  45404. return true;
  45405. }
  45406. if (this._reflectivityTexture === texture) {
  45407. return true;
  45408. }
  45409. if (this._metallicTexture === texture) {
  45410. return true;
  45411. }
  45412. if (this._microSurfaceTexture === texture) {
  45413. return true;
  45414. }
  45415. if (this._bumpTexture === texture) {
  45416. return true;
  45417. }
  45418. if (this._lightmapTexture === texture) {
  45419. return true;
  45420. }
  45421. if (this._refractionTexture === texture) {
  45422. return true;
  45423. }
  45424. return false;
  45425. };
  45426. /**
  45427. * Makes a duplicate of the current material.
  45428. * @param name - name to use for the new material.
  45429. */
  45430. PBRMaterial.prototype.clone = function (name) {
  45431. var _this = this;
  45432. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45433. clone.id = name;
  45434. clone.name = name;
  45435. return clone;
  45436. };
  45437. /**
  45438. * Serializes this PBR Material.
  45439. * @returns - An object with the serialized material.
  45440. */
  45441. PBRMaterial.prototype.serialize = function () {
  45442. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45443. serializationObject.customType = "BABYLON.PBRMaterial";
  45444. return serializationObject;
  45445. };
  45446. // Statics
  45447. /**
  45448. * Parses a PBR Material from a serialized object.
  45449. * @param source - Serialized object.
  45450. * @param scene - BJS scene instance.
  45451. * @param rootUrl - url for the scene object
  45452. * @returns - PBRMaterial
  45453. */
  45454. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45455. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45456. };
  45457. /**
  45458. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45459. */
  45460. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45461. /**
  45462. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45463. */
  45464. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45465. /**
  45466. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45467. */
  45468. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45469. /**
  45470. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45471. * They are also discarded below the alpha cutoff threshold to improve performances.
  45472. */
  45473. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45474. __decorate([
  45475. BABYLON.serialize(),
  45476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45477. ], PBRMaterial.prototype, "directIntensity", void 0);
  45478. __decorate([
  45479. BABYLON.serialize(),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45481. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45482. __decorate([
  45483. BABYLON.serialize(),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45485. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45486. __decorate([
  45487. BABYLON.serialize(),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45489. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45490. __decorate([
  45491. BABYLON.serialize(),
  45492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45493. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45494. __decorate([
  45495. BABYLON.serializeAsTexture(),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45497. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45498. __decorate([
  45499. BABYLON.serializeAsTexture(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45502. __decorate([
  45503. BABYLON.serialize(),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45505. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45506. __decorate([
  45507. BABYLON.serializeAsTexture(),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45509. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45510. __decorate([
  45511. BABYLON.serializeAsTexture(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45514. __decorate([
  45515. BABYLON.serializeAsTexture(),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45517. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45518. __decorate([
  45519. BABYLON.serializeAsTexture(),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45521. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45522. __decorate([
  45523. BABYLON.serializeAsTexture(),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45526. __decorate([
  45527. BABYLON.serialize(),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45529. ], PBRMaterial.prototype, "metallic", void 0);
  45530. __decorate([
  45531. BABYLON.serialize(),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "roughness", void 0);
  45534. __decorate([
  45535. BABYLON.serializeAsTexture(),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45538. __decorate([
  45539. BABYLON.serializeAsTexture(),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45541. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45542. __decorate([
  45543. BABYLON.serializeAsTexture(),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45545. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45546. __decorate([
  45547. BABYLON.serializeAsTexture(),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45549. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45550. __decorate([
  45551. BABYLON.serializeAsColor3("ambient"),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45553. ], PBRMaterial.prototype, "ambientColor", void 0);
  45554. __decorate([
  45555. BABYLON.serializeAsColor3("albedo"),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "albedoColor", void 0);
  45558. __decorate([
  45559. BABYLON.serializeAsColor3("reflectivity"),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45562. __decorate([
  45563. BABYLON.serializeAsColor3("reflection"),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45565. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45566. __decorate([
  45567. BABYLON.serializeAsColor3("emissive"),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45569. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45570. __decorate([
  45571. BABYLON.serialize(),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45573. ], PBRMaterial.prototype, "microSurface", void 0);
  45574. __decorate([
  45575. BABYLON.serialize(),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45577. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45578. __decorate([
  45579. BABYLON.serialize(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45581. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45582. __decorate([
  45583. BABYLON.serialize(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45586. __decorate([
  45587. BABYLON.serialize(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45589. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45593. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45597. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45598. __decorate([
  45599. BABYLON.serialize(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45601. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45613. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45634. __decorate([
  45635. BABYLON.serialize()
  45636. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45637. __decorate([
  45638. BABYLON.serialize()
  45639. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45640. __decorate([
  45641. BABYLON.serialize(),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45643. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45644. __decorate([
  45645. BABYLON.serialize(),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45647. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45648. __decorate([
  45649. BABYLON.serialize(),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45651. ], PBRMaterial.prototype, "useParallax", void 0);
  45652. __decorate([
  45653. BABYLON.serialize(),
  45654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45655. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45656. __decorate([
  45657. BABYLON.serialize(),
  45658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45659. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45660. __decorate([
  45661. BABYLON.serialize(),
  45662. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45663. ], PBRMaterial.prototype, "disableLighting", void 0);
  45664. __decorate([
  45665. BABYLON.serialize(),
  45666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45667. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45668. __decorate([
  45669. BABYLON.serialize(),
  45670. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45671. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45672. __decorate([
  45673. BABYLON.serialize(),
  45674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45675. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45676. __decorate([
  45677. BABYLON.serialize(),
  45678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45679. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45680. __decorate([
  45681. BABYLON.serialize(),
  45682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45683. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45684. __decorate([
  45685. BABYLON.serialize(),
  45686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45687. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45688. __decorate([
  45689. BABYLON.serialize(),
  45690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45691. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45692. __decorate([
  45693. BABYLON.serializeAsTexture(),
  45694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45695. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45696. __decorate([
  45697. BABYLON.serialize(),
  45698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45699. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45700. __decorate([
  45701. BABYLON.serialize(),
  45702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45703. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45704. __decorate([
  45705. BABYLON.serialize(),
  45706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45707. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45708. __decorate([
  45709. BABYLON.serialize(),
  45710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45711. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45712. __decorate([
  45713. BABYLON.serialize(),
  45714. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45715. ], PBRMaterial.prototype, "unlit", void 0);
  45716. return PBRMaterial;
  45717. }(BABYLON.PBRBaseMaterial));
  45718. BABYLON.PBRMaterial = PBRMaterial;
  45719. })(BABYLON || (BABYLON = {}));
  45720. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45721. var BABYLON;
  45722. (function (BABYLON) {
  45723. /**
  45724. * The PBR material of BJS following the metal roughness convention.
  45725. *
  45726. * This fits to the PBR convention in the GLTF definition:
  45727. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45728. */
  45729. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45730. __extends(PBRMetallicRoughnessMaterial, _super);
  45731. /**
  45732. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45733. *
  45734. * @param name The material name
  45735. * @param scene The scene the material will be use in.
  45736. */
  45737. function PBRMetallicRoughnessMaterial(name, scene) {
  45738. var _this = _super.call(this, name, scene) || this;
  45739. _this._useRoughnessFromMetallicTextureAlpha = false;
  45740. _this._useRoughnessFromMetallicTextureGreen = true;
  45741. _this._useMetallnessFromMetallicTextureBlue = true;
  45742. _this.metallic = 1.0;
  45743. _this.roughness = 1.0;
  45744. return _this;
  45745. }
  45746. /**
  45747. * Return the currrent class name of the material.
  45748. */
  45749. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45750. return "PBRMetallicRoughnessMaterial";
  45751. };
  45752. /**
  45753. * Return the active textures of the material.
  45754. */
  45755. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45756. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45757. if (this.baseTexture) {
  45758. activeTextures.push(this.baseTexture);
  45759. }
  45760. if (this.metallicRoughnessTexture) {
  45761. activeTextures.push(this.metallicRoughnessTexture);
  45762. }
  45763. return activeTextures;
  45764. };
  45765. /**
  45766. * Checks to see if a texture is used in the material.
  45767. * @param texture - Base texture to use.
  45768. * @returns - Boolean specifying if a texture is used in the material.
  45769. */
  45770. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45771. if (_super.prototype.hasTexture.call(this, texture)) {
  45772. return true;
  45773. }
  45774. if (this.baseTexture === texture) {
  45775. return true;
  45776. }
  45777. if (this.metallicRoughnessTexture === texture) {
  45778. return true;
  45779. }
  45780. return false;
  45781. };
  45782. /**
  45783. * Makes a duplicate of the current material.
  45784. * @param name - name to use for the new material.
  45785. */
  45786. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45787. var _this = this;
  45788. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45789. clone.id = name;
  45790. clone.name = name;
  45791. return clone;
  45792. };
  45793. /**
  45794. * Serialize the material to a parsable JSON object.
  45795. */
  45796. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45797. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45798. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45799. return serializationObject;
  45800. };
  45801. /**
  45802. * Parses a JSON object correponding to the serialize function.
  45803. */
  45804. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45805. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45806. };
  45807. __decorate([
  45808. BABYLON.serializeAsColor3(),
  45809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45810. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45811. __decorate([
  45812. BABYLON.serializeAsTexture(),
  45813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45814. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45815. __decorate([
  45816. BABYLON.serialize(),
  45817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45818. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45819. __decorate([
  45820. BABYLON.serialize(),
  45821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45822. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45823. __decorate([
  45824. BABYLON.serializeAsTexture(),
  45825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45826. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45827. return PBRMetallicRoughnessMaterial;
  45828. }(BABYLON.PBRBaseSimpleMaterial));
  45829. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45830. })(BABYLON || (BABYLON = {}));
  45831. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45832. var BABYLON;
  45833. (function (BABYLON) {
  45834. /**
  45835. * The PBR material of BJS following the specular glossiness convention.
  45836. *
  45837. * This fits to the PBR convention in the GLTF definition:
  45838. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45839. */
  45840. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45841. __extends(PBRSpecularGlossinessMaterial, _super);
  45842. /**
  45843. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45844. *
  45845. * @param name The material name
  45846. * @param scene The scene the material will be use in.
  45847. */
  45848. function PBRSpecularGlossinessMaterial(name, scene) {
  45849. var _this = _super.call(this, name, scene) || this;
  45850. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45851. return _this;
  45852. }
  45853. /**
  45854. * Return the currrent class name of the material.
  45855. */
  45856. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45857. return "PBRSpecularGlossinessMaterial";
  45858. };
  45859. /**
  45860. * Return the active textures of the material.
  45861. */
  45862. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45863. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45864. if (this.diffuseTexture) {
  45865. activeTextures.push(this.diffuseTexture);
  45866. }
  45867. if (this.specularGlossinessTexture) {
  45868. activeTextures.push(this.specularGlossinessTexture);
  45869. }
  45870. return activeTextures;
  45871. };
  45872. /**
  45873. * Checks to see if a texture is used in the material.
  45874. * @param texture - Base texture to use.
  45875. * @returns - Boolean specifying if a texture is used in the material.
  45876. */
  45877. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45878. if (_super.prototype.hasTexture.call(this, texture)) {
  45879. return true;
  45880. }
  45881. if (this.diffuseTexture === texture) {
  45882. return true;
  45883. }
  45884. if (this.specularGlossinessTexture === texture) {
  45885. return true;
  45886. }
  45887. return false;
  45888. };
  45889. /**
  45890. * Makes a duplicate of the current material.
  45891. * @param name - name to use for the new material.
  45892. */
  45893. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45894. var _this = this;
  45895. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45896. clone.id = name;
  45897. clone.name = name;
  45898. return clone;
  45899. };
  45900. /**
  45901. * Serialize the material to a parsable JSON object.
  45902. */
  45903. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45904. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45905. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45906. return serializationObject;
  45907. };
  45908. /**
  45909. * Parses a JSON object correponding to the serialize function.
  45910. */
  45911. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45912. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45913. };
  45914. __decorate([
  45915. BABYLON.serializeAsColor3("diffuse"),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45917. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45918. __decorate([
  45919. BABYLON.serializeAsTexture(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45921. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45922. __decorate([
  45923. BABYLON.serializeAsColor3("specular"),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45925. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45926. __decorate([
  45927. BABYLON.serialize(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45929. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45930. __decorate([
  45931. BABYLON.serializeAsTexture(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45933. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45934. return PBRSpecularGlossinessMaterial;
  45935. }(BABYLON.PBRBaseSimpleMaterial));
  45936. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45937. })(BABYLON || (BABYLON = {}));
  45938. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45939. var BABYLON;
  45940. (function (BABYLON) {
  45941. BABYLON.CameraInputTypes = {};
  45942. var CameraInputsManager = /** @class */ (function () {
  45943. function CameraInputsManager(camera) {
  45944. this.attached = {};
  45945. this.camera = camera;
  45946. this.checkInputs = function () { };
  45947. }
  45948. /**
  45949. * Add an input method to a camera
  45950. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45951. * @param input camera input method
  45952. */
  45953. CameraInputsManager.prototype.add = function (input) {
  45954. var type = input.getSimpleName();
  45955. if (this.attached[type]) {
  45956. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45957. return;
  45958. }
  45959. this.attached[type] = input;
  45960. input.camera = this.camera;
  45961. //for checkInputs, we are dynamically creating a function
  45962. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45963. if (input.checkInputs) {
  45964. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45965. }
  45966. if (this.attachedElement) {
  45967. input.attachControl(this.attachedElement);
  45968. }
  45969. };
  45970. /**
  45971. * Remove a specific input method from a camera
  45972. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45973. * @param inputToRemove camera input method
  45974. */
  45975. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45976. for (var cam in this.attached) {
  45977. var input = this.attached[cam];
  45978. if (input === inputToRemove) {
  45979. input.detachControl(this.attachedElement);
  45980. input.camera = null;
  45981. delete this.attached[cam];
  45982. this.rebuildInputCheck();
  45983. }
  45984. }
  45985. };
  45986. CameraInputsManager.prototype.removeByType = function (inputType) {
  45987. for (var cam in this.attached) {
  45988. var input = this.attached[cam];
  45989. if (input.getClassName() === inputType) {
  45990. input.detachControl(this.attachedElement);
  45991. input.camera = null;
  45992. delete this.attached[cam];
  45993. this.rebuildInputCheck();
  45994. }
  45995. }
  45996. };
  45997. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45998. var current = this.checkInputs;
  45999. return function () {
  46000. current();
  46001. fn();
  46002. };
  46003. };
  46004. CameraInputsManager.prototype.attachInput = function (input) {
  46005. if (this.attachedElement) {
  46006. input.attachControl(this.attachedElement, this.noPreventDefault);
  46007. }
  46008. };
  46009. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46010. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46011. if (this.attachedElement) {
  46012. return;
  46013. }
  46014. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46015. this.attachedElement = element;
  46016. this.noPreventDefault = noPreventDefault;
  46017. for (var cam in this.attached) {
  46018. this.attached[cam].attachControl(element, noPreventDefault);
  46019. }
  46020. };
  46021. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46022. if (disconnect === void 0) { disconnect = false; }
  46023. if (this.attachedElement !== element) {
  46024. return;
  46025. }
  46026. for (var cam in this.attached) {
  46027. this.attached[cam].detachControl(element);
  46028. if (disconnect) {
  46029. this.attached[cam].camera = null;
  46030. }
  46031. }
  46032. this.attachedElement = null;
  46033. };
  46034. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46035. this.checkInputs = function () { };
  46036. for (var cam in this.attached) {
  46037. var input = this.attached[cam];
  46038. if (input.checkInputs) {
  46039. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46040. }
  46041. }
  46042. };
  46043. /**
  46044. * Remove all attached input methods from a camera
  46045. */
  46046. CameraInputsManager.prototype.clear = function () {
  46047. if (this.attachedElement) {
  46048. this.detachElement(this.attachedElement, true);
  46049. }
  46050. this.attached = {};
  46051. this.attachedElement = null;
  46052. this.checkInputs = function () { };
  46053. };
  46054. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46055. var inputs = {};
  46056. for (var cam in this.attached) {
  46057. var input = this.attached[cam];
  46058. var res = BABYLON.SerializationHelper.Serialize(input);
  46059. inputs[input.getClassName()] = res;
  46060. }
  46061. serializedCamera.inputsmgr = inputs;
  46062. };
  46063. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46064. var parsedInputs = parsedCamera.inputsmgr;
  46065. if (parsedInputs) {
  46066. this.clear();
  46067. for (var n in parsedInputs) {
  46068. var construct = BABYLON.CameraInputTypes[n];
  46069. if (construct) {
  46070. var parsedinput = parsedInputs[n];
  46071. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46072. this.add(input);
  46073. }
  46074. }
  46075. }
  46076. else {
  46077. //2016-03-08 this part is for managing backward compatibility
  46078. for (var n in this.attached) {
  46079. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46080. if (construct) {
  46081. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46082. this.remove(this.attached[n]);
  46083. this.add(input);
  46084. }
  46085. }
  46086. }
  46087. };
  46088. return CameraInputsManager;
  46089. }());
  46090. BABYLON.CameraInputsManager = CameraInputsManager;
  46091. })(BABYLON || (BABYLON = {}));
  46092. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46093. var BABYLON;
  46094. (function (BABYLON) {
  46095. var TargetCamera = /** @class */ (function (_super) {
  46096. __extends(TargetCamera, _super);
  46097. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46098. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46099. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46100. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46101. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46102. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46103. _this.speed = 2.0;
  46104. _this.noRotationConstraint = false;
  46105. _this.lockedTarget = null;
  46106. _this._currentTarget = BABYLON.Vector3.Zero();
  46107. _this._viewMatrix = BABYLON.Matrix.Zero();
  46108. _this._camMatrix = BABYLON.Matrix.Zero();
  46109. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46110. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46111. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46112. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46113. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46114. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46115. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46116. return _this;
  46117. }
  46118. TargetCamera.prototype.getFrontPosition = function (distance) {
  46119. this.getWorldMatrix();
  46120. var direction = this.getTarget().subtract(this.position);
  46121. direction.normalize();
  46122. direction.scaleInPlace(distance);
  46123. return this.globalPosition.add(direction);
  46124. };
  46125. TargetCamera.prototype._getLockedTargetPosition = function () {
  46126. if (!this.lockedTarget) {
  46127. return null;
  46128. }
  46129. if (this.lockedTarget.absolutePosition) {
  46130. this.lockedTarget.computeWorldMatrix();
  46131. }
  46132. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46133. };
  46134. TargetCamera.prototype.storeState = function () {
  46135. this._storedPosition = this.position.clone();
  46136. this._storedRotation = this.rotation.clone();
  46137. if (this.rotationQuaternion) {
  46138. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46139. }
  46140. return _super.prototype.storeState.call(this);
  46141. };
  46142. /**
  46143. * Restored camera state. You must call storeState() first
  46144. */
  46145. TargetCamera.prototype._restoreStateValues = function () {
  46146. if (!_super.prototype._restoreStateValues.call(this)) {
  46147. return false;
  46148. }
  46149. this.position = this._storedPosition.clone();
  46150. this.rotation = this._storedRotation.clone();
  46151. if (this.rotationQuaternion) {
  46152. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46153. }
  46154. this.cameraDirection.copyFromFloats(0, 0, 0);
  46155. this.cameraRotation.copyFromFloats(0, 0);
  46156. return true;
  46157. };
  46158. // Cache
  46159. TargetCamera.prototype._initCache = function () {
  46160. _super.prototype._initCache.call(this);
  46161. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46162. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46163. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46164. };
  46165. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46166. if (!ignoreParentClass) {
  46167. _super.prototype._updateCache.call(this);
  46168. }
  46169. var lockedTargetPosition = this._getLockedTargetPosition();
  46170. if (!lockedTargetPosition) {
  46171. this._cache.lockedTarget = null;
  46172. }
  46173. else {
  46174. if (!this._cache.lockedTarget) {
  46175. this._cache.lockedTarget = lockedTargetPosition.clone();
  46176. }
  46177. else {
  46178. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46179. }
  46180. }
  46181. this._cache.rotation.copyFrom(this.rotation);
  46182. if (this.rotationQuaternion)
  46183. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46184. };
  46185. // Synchronized
  46186. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46187. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46188. return false;
  46189. }
  46190. var lockedTargetPosition = this._getLockedTargetPosition();
  46191. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46192. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46193. };
  46194. // Methods
  46195. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46196. var engine = this.getEngine();
  46197. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46198. };
  46199. // Target
  46200. TargetCamera.prototype.setTarget = function (target) {
  46201. this.upVector.normalize();
  46202. if (this.position.z === target.z) {
  46203. this.position.z += BABYLON.Epsilon;
  46204. }
  46205. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46206. this._camMatrix.invert();
  46207. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46208. var vDir = target.subtract(this.position);
  46209. if (vDir.x >= 0.0) {
  46210. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46211. }
  46212. else {
  46213. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46214. }
  46215. this.rotation.z = 0;
  46216. if (isNaN(this.rotation.x)) {
  46217. this.rotation.x = 0;
  46218. }
  46219. if (isNaN(this.rotation.y)) {
  46220. this.rotation.y = 0;
  46221. }
  46222. if (isNaN(this.rotation.z)) {
  46223. this.rotation.z = 0;
  46224. }
  46225. if (this.rotationQuaternion) {
  46226. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46227. }
  46228. };
  46229. /**
  46230. * Return the current target position of the camera. This value is expressed in local space.
  46231. */
  46232. TargetCamera.prototype.getTarget = function () {
  46233. return this._currentTarget;
  46234. };
  46235. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46236. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46237. };
  46238. TargetCamera.prototype._updatePosition = function () {
  46239. if (this.parent) {
  46240. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46241. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46242. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46243. return;
  46244. }
  46245. this.position.addInPlace(this.cameraDirection);
  46246. };
  46247. TargetCamera.prototype._checkInputs = function () {
  46248. var needToMove = this._decideIfNeedsToMove();
  46249. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46250. // Move
  46251. if (needToMove) {
  46252. this._updatePosition();
  46253. }
  46254. // Rotate
  46255. if (needToRotate) {
  46256. this.rotation.x += this.cameraRotation.x;
  46257. this.rotation.y += this.cameraRotation.y;
  46258. //rotate, if quaternion is set and rotation was used
  46259. if (this.rotationQuaternion) {
  46260. var len = this.rotation.lengthSquared();
  46261. if (len) {
  46262. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46263. }
  46264. }
  46265. if (!this.noRotationConstraint) {
  46266. var limit = (Math.PI / 2) * 0.95;
  46267. if (this.rotation.x > limit)
  46268. this.rotation.x = limit;
  46269. if (this.rotation.x < -limit)
  46270. this.rotation.x = -limit;
  46271. }
  46272. }
  46273. // Inertia
  46274. if (needToMove) {
  46275. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46276. this.cameraDirection.x = 0;
  46277. }
  46278. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46279. this.cameraDirection.y = 0;
  46280. }
  46281. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46282. this.cameraDirection.z = 0;
  46283. }
  46284. this.cameraDirection.scaleInPlace(this.inertia);
  46285. }
  46286. if (needToRotate) {
  46287. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46288. this.cameraRotation.x = 0;
  46289. }
  46290. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46291. this.cameraRotation.y = 0;
  46292. }
  46293. this.cameraRotation.scaleInPlace(this.inertia);
  46294. }
  46295. _super.prototype._checkInputs.call(this);
  46296. };
  46297. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46298. if (this.rotationQuaternion) {
  46299. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46300. }
  46301. else {
  46302. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46303. }
  46304. //update the up vector!
  46305. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46306. };
  46307. TargetCamera.prototype._getViewMatrix = function () {
  46308. if (this.lockedTarget) {
  46309. this.setTarget(this._getLockedTargetPosition());
  46310. }
  46311. // Compute
  46312. this._updateCameraRotationMatrix();
  46313. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46314. // Computing target and final matrix
  46315. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46316. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46317. return this._viewMatrix;
  46318. };
  46319. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46320. if (this.parent) {
  46321. var parentWorldMatrix = this.parent.getWorldMatrix();
  46322. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46323. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46324. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46325. this._markSyncedWithParent();
  46326. }
  46327. else {
  46328. this._globalPosition.copyFrom(position);
  46329. this._globalCurrentTarget.copyFrom(target);
  46330. this._globalCurrentUpVector.copyFrom(up);
  46331. }
  46332. if (this.getScene().useRightHandedSystem) {
  46333. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46334. }
  46335. else {
  46336. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46337. }
  46338. };
  46339. /**
  46340. * @override
  46341. * Override Camera.createRigCamera
  46342. */
  46343. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46344. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46345. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46346. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46347. if (!this.rotationQuaternion) {
  46348. this.rotationQuaternion = new BABYLON.Quaternion();
  46349. }
  46350. rigCamera._cameraRigParams = {};
  46351. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46352. }
  46353. return rigCamera;
  46354. }
  46355. return null;
  46356. };
  46357. /**
  46358. * @override
  46359. * Override Camera._updateRigCameras
  46360. */
  46361. TargetCamera.prototype._updateRigCameras = function () {
  46362. var camLeft = this._rigCameras[0];
  46363. var camRight = this._rigCameras[1];
  46364. switch (this.cameraRigMode) {
  46365. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46366. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46367. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46368. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46369. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46370. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46371. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46372. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46373. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46374. camLeft.setTarget(this.getTarget());
  46375. camRight.setTarget(this.getTarget());
  46376. break;
  46377. case BABYLON.Camera.RIG_MODE_VR:
  46378. if (camLeft.rotationQuaternion) {
  46379. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46380. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46381. }
  46382. else {
  46383. camLeft.rotation.copyFrom(this.rotation);
  46384. camRight.rotation.copyFrom(this.rotation);
  46385. }
  46386. camLeft.position.copyFrom(this.position);
  46387. camRight.position.copyFrom(this.position);
  46388. break;
  46389. }
  46390. _super.prototype._updateRigCameras.call(this);
  46391. };
  46392. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46393. if (!this._rigCamTransformMatrix) {
  46394. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46395. }
  46396. var target = this.getTarget();
  46397. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46398. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46399. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46400. };
  46401. TargetCamera.prototype.getClassName = function () {
  46402. return "TargetCamera";
  46403. };
  46404. __decorate([
  46405. BABYLON.serializeAsVector3()
  46406. ], TargetCamera.prototype, "rotation", void 0);
  46407. __decorate([
  46408. BABYLON.serialize()
  46409. ], TargetCamera.prototype, "speed", void 0);
  46410. __decorate([
  46411. BABYLON.serializeAsMeshReference("lockedTargetId")
  46412. ], TargetCamera.prototype, "lockedTarget", void 0);
  46413. return TargetCamera;
  46414. }(BABYLON.Camera));
  46415. BABYLON.TargetCamera = TargetCamera;
  46416. })(BABYLON || (BABYLON = {}));
  46417. //# sourceMappingURL=babylon.targetCamera.js.map
  46418. var BABYLON;
  46419. (function (BABYLON) {
  46420. var FreeCameraMouseInput = /** @class */ (function () {
  46421. function FreeCameraMouseInput(touchEnabled) {
  46422. if (touchEnabled === void 0) { touchEnabled = true; }
  46423. this.touchEnabled = touchEnabled;
  46424. this.buttons = [0, 1, 2];
  46425. this.angularSensibility = 2000.0;
  46426. this.previousPosition = null;
  46427. }
  46428. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46429. var _this = this;
  46430. var engine = this.camera.getEngine();
  46431. if (!this._pointerInput) {
  46432. this._pointerInput = function (p, s) {
  46433. var evt = p.event;
  46434. if (engine.isInVRExclusivePointerMode) {
  46435. return;
  46436. }
  46437. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46438. return;
  46439. }
  46440. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46441. return;
  46442. }
  46443. var srcElement = (evt.srcElement || evt.target);
  46444. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46445. try {
  46446. srcElement.setPointerCapture(evt.pointerId);
  46447. }
  46448. catch (e) {
  46449. //Nothing to do with the error. Execution will continue.
  46450. }
  46451. _this.previousPosition = {
  46452. x: evt.clientX,
  46453. y: evt.clientY
  46454. };
  46455. if (!noPreventDefault) {
  46456. evt.preventDefault();
  46457. element.focus();
  46458. }
  46459. }
  46460. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46461. try {
  46462. srcElement.releasePointerCapture(evt.pointerId);
  46463. }
  46464. catch (e) {
  46465. //Nothing to do with the error.
  46466. }
  46467. _this.previousPosition = null;
  46468. if (!noPreventDefault) {
  46469. evt.preventDefault();
  46470. }
  46471. }
  46472. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46473. if (!_this.previousPosition || engine.isPointerLock) {
  46474. return;
  46475. }
  46476. var offsetX = evt.clientX - _this.previousPosition.x;
  46477. if (_this.camera.getScene().useRightHandedSystem)
  46478. offsetX *= -1;
  46479. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46480. offsetX *= -1;
  46481. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46482. var offsetY = evt.clientY - _this.previousPosition.y;
  46483. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46484. _this.previousPosition = {
  46485. x: evt.clientX,
  46486. y: evt.clientY
  46487. };
  46488. if (!noPreventDefault) {
  46489. evt.preventDefault();
  46490. }
  46491. }
  46492. };
  46493. }
  46494. this._onMouseMove = function (evt) {
  46495. if (!engine.isPointerLock) {
  46496. return;
  46497. }
  46498. if (engine.isInVRExclusivePointerMode) {
  46499. return;
  46500. }
  46501. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46502. if (_this.camera.getScene().useRightHandedSystem)
  46503. offsetX *= -1;
  46504. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46505. offsetX *= -1;
  46506. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46507. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46508. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46509. _this.previousPosition = null;
  46510. if (!noPreventDefault) {
  46511. evt.preventDefault();
  46512. }
  46513. };
  46514. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46515. element.addEventListener("mousemove", this._onMouseMove, false);
  46516. };
  46517. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46518. if (this._observer && element) {
  46519. this.camera.getScene().onPointerObservable.remove(this._observer);
  46520. if (this._onMouseMove) {
  46521. element.removeEventListener("mousemove", this._onMouseMove);
  46522. }
  46523. this._observer = null;
  46524. this._onMouseMove = null;
  46525. this.previousPosition = null;
  46526. }
  46527. };
  46528. FreeCameraMouseInput.prototype.getClassName = function () {
  46529. return "FreeCameraMouseInput";
  46530. };
  46531. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46532. return "mouse";
  46533. };
  46534. __decorate([
  46535. BABYLON.serialize()
  46536. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46537. __decorate([
  46538. BABYLON.serialize()
  46539. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46540. return FreeCameraMouseInput;
  46541. }());
  46542. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46543. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46544. })(BABYLON || (BABYLON = {}));
  46545. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46546. var BABYLON;
  46547. (function (BABYLON) {
  46548. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46549. function FreeCameraKeyboardMoveInput() {
  46550. this._keys = new Array();
  46551. this.keysUp = [38];
  46552. this.keysDown = [40];
  46553. this.keysLeft = [37];
  46554. this.keysRight = [39];
  46555. }
  46556. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46557. var _this = this;
  46558. if (this._onCanvasBlurObserver) {
  46559. return;
  46560. }
  46561. this._scene = this.camera.getScene();
  46562. this._engine = this._scene.getEngine();
  46563. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46564. _this._keys = [];
  46565. });
  46566. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46567. var evt = info.event;
  46568. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46569. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46570. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46571. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46572. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46573. var index = _this._keys.indexOf(evt.keyCode);
  46574. if (index === -1) {
  46575. _this._keys.push(evt.keyCode);
  46576. }
  46577. if (!noPreventDefault) {
  46578. evt.preventDefault();
  46579. }
  46580. }
  46581. }
  46582. else {
  46583. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46584. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46585. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46586. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46587. var index = _this._keys.indexOf(evt.keyCode);
  46588. if (index >= 0) {
  46589. _this._keys.splice(index, 1);
  46590. }
  46591. if (!noPreventDefault) {
  46592. evt.preventDefault();
  46593. }
  46594. }
  46595. }
  46596. });
  46597. };
  46598. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46599. if (this._scene) {
  46600. if (this._onKeyboardObserver) {
  46601. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46602. }
  46603. if (this._onCanvasBlurObserver) {
  46604. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46605. }
  46606. this._onKeyboardObserver = null;
  46607. this._onCanvasBlurObserver = null;
  46608. }
  46609. this._keys = [];
  46610. };
  46611. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46612. if (this._onKeyboardObserver) {
  46613. var camera = this.camera;
  46614. // Keyboard
  46615. for (var index = 0; index < this._keys.length; index++) {
  46616. var keyCode = this._keys[index];
  46617. var speed = camera._computeLocalCameraSpeed();
  46618. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46619. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46620. }
  46621. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46622. camera._localDirection.copyFromFloats(0, 0, speed);
  46623. }
  46624. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46625. camera._localDirection.copyFromFloats(speed, 0, 0);
  46626. }
  46627. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46628. camera._localDirection.copyFromFloats(0, 0, -speed);
  46629. }
  46630. if (camera.getScene().useRightHandedSystem) {
  46631. camera._localDirection.z *= -1;
  46632. }
  46633. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46634. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46635. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46636. }
  46637. }
  46638. };
  46639. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46640. return "FreeCameraKeyboardMoveInput";
  46641. };
  46642. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46643. this._keys = [];
  46644. };
  46645. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46646. return "keyboard";
  46647. };
  46648. __decorate([
  46649. BABYLON.serialize()
  46650. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46651. __decorate([
  46652. BABYLON.serialize()
  46653. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46654. __decorate([
  46655. BABYLON.serialize()
  46656. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46657. __decorate([
  46658. BABYLON.serialize()
  46659. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46660. return FreeCameraKeyboardMoveInput;
  46661. }());
  46662. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46663. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46664. })(BABYLON || (BABYLON = {}));
  46665. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46666. var BABYLON;
  46667. (function (BABYLON) {
  46668. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46669. __extends(FreeCameraInputsManager, _super);
  46670. function FreeCameraInputsManager(camera) {
  46671. return _super.call(this, camera) || this;
  46672. }
  46673. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46674. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46675. return this;
  46676. };
  46677. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46678. if (touchEnabled === void 0) { touchEnabled = true; }
  46679. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46680. return this;
  46681. };
  46682. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46683. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46684. return this;
  46685. };
  46686. FreeCameraInputsManager.prototype.addTouch = function () {
  46687. this.add(new BABYLON.FreeCameraTouchInput());
  46688. return this;
  46689. };
  46690. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46691. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46692. return this;
  46693. };
  46694. return FreeCameraInputsManager;
  46695. }(BABYLON.CameraInputsManager));
  46696. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46697. })(BABYLON || (BABYLON = {}));
  46698. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46699. var BABYLON;
  46700. (function (BABYLON) {
  46701. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46702. // Forcing to use the Universal camera
  46703. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46704. });
  46705. var FreeCamera = /** @class */ (function (_super) {
  46706. __extends(FreeCamera, _super);
  46707. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46708. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46709. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46710. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46711. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46712. _this.checkCollisions = false;
  46713. _this.applyGravity = false;
  46714. _this._needMoveForGravity = false;
  46715. _this._oldPosition = BABYLON.Vector3.Zero();
  46716. _this._diffPosition = BABYLON.Vector3.Zero();
  46717. _this._newPosition = BABYLON.Vector3.Zero();
  46718. // Collisions
  46719. _this._collisionMask = -1;
  46720. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46721. if (collidedMesh === void 0) { collidedMesh = null; }
  46722. //TODO move this to the collision coordinator!
  46723. if (_this.getScene().workerCollisions)
  46724. newPosition.multiplyInPlace(_this._collider._radius);
  46725. var updatePosition = function (newPos) {
  46726. _this._newPosition.copyFrom(newPos);
  46727. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46728. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46729. _this.position.addInPlace(_this._diffPosition);
  46730. if (_this.onCollide && collidedMesh) {
  46731. _this.onCollide(collidedMesh);
  46732. }
  46733. }
  46734. };
  46735. updatePosition(newPosition);
  46736. };
  46737. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46738. _this.inputs.addKeyboard().addMouse();
  46739. return _this;
  46740. }
  46741. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46742. //-- begin properties for backward compatibility for inputs
  46743. /**
  46744. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46745. * Higher values reduce sensitivity.
  46746. */
  46747. get: function () {
  46748. var mouse = this.inputs.attached["mouse"];
  46749. if (mouse)
  46750. return mouse.angularSensibility;
  46751. return 0;
  46752. },
  46753. /**
  46754. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46755. * Higher values reduce sensitivity.
  46756. */
  46757. set: function (value) {
  46758. var mouse = this.inputs.attached["mouse"];
  46759. if (mouse)
  46760. mouse.angularSensibility = value;
  46761. },
  46762. enumerable: true,
  46763. configurable: true
  46764. });
  46765. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46766. get: function () {
  46767. var keyboard = this.inputs.attached["keyboard"];
  46768. if (keyboard)
  46769. return keyboard.keysUp;
  46770. return [];
  46771. },
  46772. set: function (value) {
  46773. var keyboard = this.inputs.attached["keyboard"];
  46774. if (keyboard)
  46775. keyboard.keysUp = value;
  46776. },
  46777. enumerable: true,
  46778. configurable: true
  46779. });
  46780. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46781. get: function () {
  46782. var keyboard = this.inputs.attached["keyboard"];
  46783. if (keyboard)
  46784. return keyboard.keysDown;
  46785. return [];
  46786. },
  46787. set: function (value) {
  46788. var keyboard = this.inputs.attached["keyboard"];
  46789. if (keyboard)
  46790. keyboard.keysDown = value;
  46791. },
  46792. enumerable: true,
  46793. configurable: true
  46794. });
  46795. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46796. get: function () {
  46797. var keyboard = this.inputs.attached["keyboard"];
  46798. if (keyboard)
  46799. return keyboard.keysLeft;
  46800. return [];
  46801. },
  46802. set: function (value) {
  46803. var keyboard = this.inputs.attached["keyboard"];
  46804. if (keyboard)
  46805. keyboard.keysLeft = value;
  46806. },
  46807. enumerable: true,
  46808. configurable: true
  46809. });
  46810. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46811. get: function () {
  46812. var keyboard = this.inputs.attached["keyboard"];
  46813. if (keyboard)
  46814. return keyboard.keysRight;
  46815. return [];
  46816. },
  46817. set: function (value) {
  46818. var keyboard = this.inputs.attached["keyboard"];
  46819. if (keyboard)
  46820. keyboard.keysRight = value;
  46821. },
  46822. enumerable: true,
  46823. configurable: true
  46824. });
  46825. // Controls
  46826. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46827. this.inputs.attachElement(element, noPreventDefault);
  46828. };
  46829. FreeCamera.prototype.detachControl = function (element) {
  46830. this.inputs.detachElement(element);
  46831. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46832. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46833. };
  46834. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46835. get: function () {
  46836. return this._collisionMask;
  46837. },
  46838. set: function (mask) {
  46839. this._collisionMask = !isNaN(mask) ? mask : -1;
  46840. },
  46841. enumerable: true,
  46842. configurable: true
  46843. });
  46844. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46845. var globalPosition;
  46846. if (this.parent) {
  46847. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46848. }
  46849. else {
  46850. globalPosition = this.position;
  46851. }
  46852. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46853. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46854. if (!this._collider) {
  46855. this._collider = new BABYLON.Collider();
  46856. }
  46857. this._collider._radius = this.ellipsoid;
  46858. this._collider.collisionMask = this._collisionMask;
  46859. //no need for clone, as long as gravity is not on.
  46860. var actualDisplacement = displacement;
  46861. //add gravity to the direction to prevent the dual-collision checking
  46862. if (this.applyGravity) {
  46863. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46864. actualDisplacement = displacement.add(this.getScene().gravity);
  46865. }
  46866. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46867. };
  46868. FreeCamera.prototype._checkInputs = function () {
  46869. if (!this._localDirection) {
  46870. this._localDirection = BABYLON.Vector3.Zero();
  46871. this._transformedDirection = BABYLON.Vector3.Zero();
  46872. }
  46873. this.inputs.checkInputs();
  46874. _super.prototype._checkInputs.call(this);
  46875. };
  46876. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46877. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46878. };
  46879. FreeCamera.prototype._updatePosition = function () {
  46880. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46881. this._collideWithWorld(this.cameraDirection);
  46882. }
  46883. else {
  46884. _super.prototype._updatePosition.call(this);
  46885. }
  46886. };
  46887. FreeCamera.prototype.dispose = function () {
  46888. this.inputs.clear();
  46889. _super.prototype.dispose.call(this);
  46890. };
  46891. FreeCamera.prototype.getClassName = function () {
  46892. return "FreeCamera";
  46893. };
  46894. __decorate([
  46895. BABYLON.serializeAsVector3()
  46896. ], FreeCamera.prototype, "ellipsoid", void 0);
  46897. __decorate([
  46898. BABYLON.serializeAsVector3()
  46899. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46900. __decorate([
  46901. BABYLON.serialize()
  46902. ], FreeCamera.prototype, "checkCollisions", void 0);
  46903. __decorate([
  46904. BABYLON.serialize()
  46905. ], FreeCamera.prototype, "applyGravity", void 0);
  46906. return FreeCamera;
  46907. }(BABYLON.TargetCamera));
  46908. BABYLON.FreeCamera = FreeCamera;
  46909. })(BABYLON || (BABYLON = {}));
  46910. //# sourceMappingURL=babylon.freeCamera.js.map
  46911. var BABYLON;
  46912. (function (BABYLON) {
  46913. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46914. function ArcRotateCameraKeyboardMoveInput() {
  46915. this._keys = new Array();
  46916. this.keysUp = [38];
  46917. this.keysDown = [40];
  46918. this.keysLeft = [37];
  46919. this.keysRight = [39];
  46920. this.keysReset = [220];
  46921. this.panningSensibility = 50.0;
  46922. this.zoomingSensibility = 25.0;
  46923. this.useAltToZoom = true;
  46924. }
  46925. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46926. var _this = this;
  46927. if (this._onCanvasBlurObserver) {
  46928. return;
  46929. }
  46930. this._scene = this.camera.getScene();
  46931. this._engine = this._scene.getEngine();
  46932. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46933. _this._keys = [];
  46934. });
  46935. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46936. var evt = info.event;
  46937. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46938. _this._ctrlPressed = evt.ctrlKey;
  46939. _this._altPressed = evt.altKey;
  46940. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46941. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46942. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46943. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46944. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46945. var index = _this._keys.indexOf(evt.keyCode);
  46946. if (index === -1) {
  46947. _this._keys.push(evt.keyCode);
  46948. }
  46949. if (evt.preventDefault) {
  46950. if (!noPreventDefault) {
  46951. evt.preventDefault();
  46952. }
  46953. }
  46954. }
  46955. }
  46956. else {
  46957. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46958. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46959. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46960. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46961. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46962. var index = _this._keys.indexOf(evt.keyCode);
  46963. if (index >= 0) {
  46964. _this._keys.splice(index, 1);
  46965. }
  46966. if (evt.preventDefault) {
  46967. if (!noPreventDefault) {
  46968. evt.preventDefault();
  46969. }
  46970. }
  46971. }
  46972. }
  46973. });
  46974. };
  46975. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46976. if (this._scene) {
  46977. if (this._onKeyboardObserver) {
  46978. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46979. }
  46980. if (this._onCanvasBlurObserver) {
  46981. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46982. }
  46983. this._onKeyboardObserver = null;
  46984. this._onCanvasBlurObserver = null;
  46985. }
  46986. this._keys = [];
  46987. };
  46988. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46989. if (this._onKeyboardObserver) {
  46990. var camera = this.camera;
  46991. for (var index = 0; index < this._keys.length; index++) {
  46992. var keyCode = this._keys[index];
  46993. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46994. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46995. camera.inertialPanningX -= 1 / this.panningSensibility;
  46996. }
  46997. else {
  46998. camera.inertialAlphaOffset -= 0.01;
  46999. }
  47000. }
  47001. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47002. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47003. camera.inertialPanningY += 1 / this.panningSensibility;
  47004. }
  47005. else if (this._altPressed && this.useAltToZoom) {
  47006. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47007. }
  47008. else {
  47009. camera.inertialBetaOffset -= 0.01;
  47010. }
  47011. }
  47012. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47013. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47014. camera.inertialPanningX += 1 / this.panningSensibility;
  47015. }
  47016. else {
  47017. camera.inertialAlphaOffset += 0.01;
  47018. }
  47019. }
  47020. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47021. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47022. camera.inertialPanningY -= 1 / this.panningSensibility;
  47023. }
  47024. else if (this._altPressed && this.useAltToZoom) {
  47025. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47026. }
  47027. else {
  47028. camera.inertialBetaOffset += 0.01;
  47029. }
  47030. }
  47031. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47032. camera.restoreState();
  47033. }
  47034. }
  47035. }
  47036. };
  47037. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47038. return "ArcRotateCameraKeyboardMoveInput";
  47039. };
  47040. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47041. return "keyboard";
  47042. };
  47043. __decorate([
  47044. BABYLON.serialize()
  47045. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47046. __decorate([
  47047. BABYLON.serialize()
  47048. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47049. __decorate([
  47050. BABYLON.serialize()
  47051. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47052. __decorate([
  47053. BABYLON.serialize()
  47054. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47055. __decorate([
  47056. BABYLON.serialize()
  47057. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47058. __decorate([
  47059. BABYLON.serialize()
  47060. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47061. __decorate([
  47062. BABYLON.serialize()
  47063. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47064. __decorate([
  47065. BABYLON.serialize()
  47066. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47067. return ArcRotateCameraKeyboardMoveInput;
  47068. }());
  47069. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47070. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47071. })(BABYLON || (BABYLON = {}));
  47072. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47073. var BABYLON;
  47074. (function (BABYLON) {
  47075. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47076. function ArcRotateCameraMouseWheelInput() {
  47077. this.wheelPrecision = 3.0;
  47078. /**
  47079. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47080. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47081. */
  47082. this.wheelDeltaPercentage = 0;
  47083. }
  47084. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47085. var _this = this;
  47086. this._wheel = function (p, s) {
  47087. //sanity check - this should be a PointerWheel event.
  47088. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47089. return;
  47090. var event = p.event;
  47091. var delta = 0;
  47092. if (event.wheelDelta) {
  47093. if (_this.wheelDeltaPercentage) {
  47094. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47095. if (event.wheelDelta > 0) {
  47096. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47097. }
  47098. else {
  47099. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47100. }
  47101. }
  47102. else {
  47103. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47104. }
  47105. }
  47106. else if (event.detail) {
  47107. delta = -event.detail / _this.wheelPrecision;
  47108. }
  47109. if (delta)
  47110. _this.camera.inertialRadiusOffset += delta;
  47111. if (event.preventDefault) {
  47112. if (!noPreventDefault) {
  47113. event.preventDefault();
  47114. }
  47115. }
  47116. };
  47117. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47118. };
  47119. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47120. if (this._observer && element) {
  47121. this.camera.getScene().onPointerObservable.remove(this._observer);
  47122. this._observer = null;
  47123. this._wheel = null;
  47124. }
  47125. };
  47126. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47127. return "ArcRotateCameraMouseWheelInput";
  47128. };
  47129. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47130. return "mousewheel";
  47131. };
  47132. __decorate([
  47133. BABYLON.serialize()
  47134. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47135. __decorate([
  47136. BABYLON.serialize()
  47137. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47138. return ArcRotateCameraMouseWheelInput;
  47139. }());
  47140. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47141. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47142. })(BABYLON || (BABYLON = {}));
  47143. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47144. var BABYLON;
  47145. (function (BABYLON) {
  47146. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47147. function ArcRotateCameraPointersInput() {
  47148. this.buttons = [0, 1, 2];
  47149. this.angularSensibilityX = 1000.0;
  47150. this.angularSensibilityY = 1000.0;
  47151. this.pinchPrecision = 12.0;
  47152. /**
  47153. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47154. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47155. */
  47156. this.pinchDeltaPercentage = 0;
  47157. this.panningSensibility = 1000.0;
  47158. this.multiTouchPanning = true;
  47159. this.multiTouchPanAndZoom = true;
  47160. this._isPanClick = false;
  47161. this.pinchInwards = true;
  47162. }
  47163. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47164. var _this = this;
  47165. var engine = this.camera.getEngine();
  47166. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47167. var pointA = null;
  47168. var pointB = null;
  47169. var previousPinchSquaredDistance = 0;
  47170. var initialDistance = 0;
  47171. var twoFingerActivityCount = 0;
  47172. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47173. this._pointerInput = function (p, s) {
  47174. var evt = p.event;
  47175. var isTouch = p.event.pointerType === "touch";
  47176. if (engine.isInVRExclusivePointerMode) {
  47177. return;
  47178. }
  47179. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47180. return;
  47181. }
  47182. var srcElement = (evt.srcElement || evt.target);
  47183. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47184. try {
  47185. srcElement.setPointerCapture(evt.pointerId);
  47186. }
  47187. catch (e) {
  47188. //Nothing to do with the error. Execution will continue.
  47189. }
  47190. // Manage panning with pan button click
  47191. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47192. // manage pointers
  47193. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47194. if (pointA === null) {
  47195. pointA = cacheSoloPointer;
  47196. }
  47197. else if (pointB === null) {
  47198. pointB = cacheSoloPointer;
  47199. }
  47200. if (!noPreventDefault) {
  47201. evt.preventDefault();
  47202. element.focus();
  47203. }
  47204. }
  47205. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47206. _this.camera.restoreState();
  47207. }
  47208. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47209. try {
  47210. srcElement.releasePointerCapture(evt.pointerId);
  47211. }
  47212. catch (e) {
  47213. //Nothing to do with the error.
  47214. }
  47215. cacheSoloPointer = null;
  47216. previousPinchSquaredDistance = 0;
  47217. previousMultiTouchPanPosition.isPaning = false;
  47218. previousMultiTouchPanPosition.isPinching = false;
  47219. twoFingerActivityCount = 0;
  47220. initialDistance = 0;
  47221. if (!isTouch) {
  47222. pointB = null; // Mouse and pen are mono pointer
  47223. }
  47224. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47225. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47226. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47227. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47228. if (engine._badOS) {
  47229. pointA = pointB = null;
  47230. }
  47231. else {
  47232. //only remove the impacted pointer in case of multitouch allowing on most
  47233. //platforms switching from rotate to zoom and pan seamlessly.
  47234. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47235. pointA = pointB;
  47236. pointB = null;
  47237. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47238. }
  47239. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47240. pointB = null;
  47241. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47242. }
  47243. else {
  47244. pointA = pointB = null;
  47245. }
  47246. }
  47247. if (!noPreventDefault) {
  47248. evt.preventDefault();
  47249. }
  47250. }
  47251. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47252. if (!noPreventDefault) {
  47253. evt.preventDefault();
  47254. }
  47255. // One button down
  47256. if (pointA && pointB === null && cacheSoloPointer) {
  47257. if (_this.panningSensibility !== 0 &&
  47258. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47259. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47260. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47261. }
  47262. else {
  47263. var offsetX = evt.clientX - cacheSoloPointer.x;
  47264. var offsetY = evt.clientY - cacheSoloPointer.y;
  47265. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47266. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47267. }
  47268. cacheSoloPointer.x = evt.clientX;
  47269. cacheSoloPointer.y = evt.clientY;
  47270. }
  47271. // Two buttons down: pinch/pan
  47272. else if (pointA && pointB) {
  47273. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47274. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47275. ed.x = evt.clientX;
  47276. ed.y = evt.clientY;
  47277. var direction = _this.pinchInwards ? 1 : -1;
  47278. var distX = pointA.x - pointB.x;
  47279. var distY = pointA.y - pointB.y;
  47280. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47281. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47282. if (previousPinchSquaredDistance === 0) {
  47283. initialDistance = pinchDistance;
  47284. previousPinchSquaredDistance = pinchSquaredDistance;
  47285. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47286. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47287. return;
  47288. }
  47289. if (_this.multiTouchPanAndZoom) {
  47290. if (_this.pinchDeltaPercentage) {
  47291. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47292. }
  47293. else {
  47294. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47295. (_this.pinchPrecision *
  47296. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47297. direction);
  47298. }
  47299. if (_this.panningSensibility !== 0) {
  47300. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47301. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47302. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47303. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47304. previousMultiTouchPanPosition.x = pointersCenterX;
  47305. previousMultiTouchPanPosition.y = pointersCenterY;
  47306. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47307. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47308. }
  47309. }
  47310. else {
  47311. twoFingerActivityCount++;
  47312. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47313. if (_this.pinchDeltaPercentage) {
  47314. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47315. }
  47316. else {
  47317. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47318. (_this.pinchPrecision *
  47319. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47320. direction);
  47321. }
  47322. previousMultiTouchPanPosition.isPaning = false;
  47323. previousMultiTouchPanPosition.isPinching = true;
  47324. }
  47325. else {
  47326. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47327. if (!previousMultiTouchPanPosition.isPaning) {
  47328. previousMultiTouchPanPosition.isPaning = true;
  47329. previousMultiTouchPanPosition.isPinching = false;
  47330. previousMultiTouchPanPosition.x = ed.x;
  47331. previousMultiTouchPanPosition.y = ed.y;
  47332. return;
  47333. }
  47334. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47335. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47336. }
  47337. }
  47338. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47339. previousMultiTouchPanPosition.x = ed.x;
  47340. previousMultiTouchPanPosition.y = ed.y;
  47341. }
  47342. }
  47343. previousPinchSquaredDistance = pinchSquaredDistance;
  47344. }
  47345. }
  47346. };
  47347. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47348. this._onContextMenu = function (evt) {
  47349. evt.preventDefault();
  47350. };
  47351. if (!this.camera._useCtrlForPanning) {
  47352. element.addEventListener("contextmenu", this._onContextMenu, false);
  47353. }
  47354. this._onLostFocus = function () {
  47355. //this._keys = [];
  47356. pointA = pointB = null;
  47357. previousPinchSquaredDistance = 0;
  47358. previousMultiTouchPanPosition.isPaning = false;
  47359. previousMultiTouchPanPosition.isPinching = false;
  47360. twoFingerActivityCount = 0;
  47361. cacheSoloPointer = null;
  47362. initialDistance = 0;
  47363. };
  47364. this._onMouseMove = function (evt) {
  47365. if (!engine.isPointerLock) {
  47366. return;
  47367. }
  47368. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47369. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47370. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47371. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47372. if (!noPreventDefault) {
  47373. evt.preventDefault();
  47374. }
  47375. };
  47376. this._onGestureStart = function (e) {
  47377. if (window.MSGesture === undefined) {
  47378. return;
  47379. }
  47380. if (!_this._MSGestureHandler) {
  47381. _this._MSGestureHandler = new MSGesture();
  47382. _this._MSGestureHandler.target = element;
  47383. }
  47384. _this._MSGestureHandler.addPointer(e.pointerId);
  47385. };
  47386. this._onGesture = function (e) {
  47387. _this.camera.radius *= e.scale;
  47388. if (e.preventDefault) {
  47389. if (!noPreventDefault) {
  47390. e.stopPropagation();
  47391. e.preventDefault();
  47392. }
  47393. }
  47394. };
  47395. element.addEventListener("mousemove", this._onMouseMove, false);
  47396. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47397. element.addEventListener("MSGestureChange", this._onGesture, false);
  47398. BABYLON.Tools.RegisterTopRootEvents([
  47399. { name: "blur", handler: this._onLostFocus }
  47400. ]);
  47401. };
  47402. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47403. if (this._onLostFocus) {
  47404. BABYLON.Tools.UnregisterTopRootEvents([
  47405. { name: "blur", handler: this._onLostFocus }
  47406. ]);
  47407. }
  47408. if (element && this._observer) {
  47409. this.camera.getScene().onPointerObservable.remove(this._observer);
  47410. this._observer = null;
  47411. if (this._onContextMenu) {
  47412. element.removeEventListener("contextmenu", this._onContextMenu);
  47413. }
  47414. if (this._onMouseMove) {
  47415. element.removeEventListener("mousemove", this._onMouseMove);
  47416. }
  47417. if (this._onGestureStart) {
  47418. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47419. }
  47420. if (this._onGesture) {
  47421. element.removeEventListener("MSGestureChange", this._onGesture);
  47422. }
  47423. this._isPanClick = false;
  47424. this.pinchInwards = true;
  47425. this._onMouseMove = null;
  47426. this._onGestureStart = null;
  47427. this._onGesture = null;
  47428. this._MSGestureHandler = null;
  47429. this._onLostFocus = null;
  47430. this._onContextMenu = null;
  47431. }
  47432. };
  47433. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47434. return "ArcRotateCameraPointersInput";
  47435. };
  47436. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47437. return "pointers";
  47438. };
  47439. __decorate([
  47440. BABYLON.serialize()
  47441. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47442. __decorate([
  47443. BABYLON.serialize()
  47444. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47445. __decorate([
  47446. BABYLON.serialize()
  47447. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47448. __decorate([
  47449. BABYLON.serialize()
  47450. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47451. __decorate([
  47452. BABYLON.serialize()
  47453. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47454. __decorate([
  47455. BABYLON.serialize()
  47456. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47457. __decorate([
  47458. BABYLON.serialize()
  47459. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47460. __decorate([
  47461. BABYLON.serialize()
  47462. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47463. return ArcRotateCameraPointersInput;
  47464. }());
  47465. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47466. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47467. })(BABYLON || (BABYLON = {}));
  47468. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47469. var BABYLON;
  47470. (function (BABYLON) {
  47471. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47472. __extends(ArcRotateCameraInputsManager, _super);
  47473. function ArcRotateCameraInputsManager(camera) {
  47474. return _super.call(this, camera) || this;
  47475. }
  47476. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47477. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47478. return this;
  47479. };
  47480. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47481. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47482. return this;
  47483. };
  47484. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47485. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47486. return this;
  47487. };
  47488. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47489. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47490. return this;
  47491. };
  47492. return ArcRotateCameraInputsManager;
  47493. }(BABYLON.CameraInputsManager));
  47494. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47495. })(BABYLON || (BABYLON = {}));
  47496. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47497. var BABYLON;
  47498. (function (BABYLON) {
  47499. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47500. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47501. });
  47502. var ArcRotateCamera = /** @class */ (function (_super) {
  47503. __extends(ArcRotateCamera, _super);
  47504. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47505. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47506. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47507. _this.inertialAlphaOffset = 0;
  47508. _this.inertialBetaOffset = 0;
  47509. _this.inertialRadiusOffset = 0;
  47510. _this.lowerAlphaLimit = null;
  47511. _this.upperAlphaLimit = null;
  47512. _this.lowerBetaLimit = 0.01;
  47513. _this.upperBetaLimit = Math.PI;
  47514. _this.lowerRadiusLimit = null;
  47515. _this.upperRadiusLimit = null;
  47516. _this.inertialPanningX = 0;
  47517. _this.inertialPanningY = 0;
  47518. _this.pinchToPanMaxDistance = 20;
  47519. _this.panningDistanceLimit = null;
  47520. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47521. _this.panningInertia = 0.9;
  47522. //-- end properties for backward compatibility for inputs
  47523. _this.zoomOnFactor = 1;
  47524. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47525. _this.allowUpsideDown = true;
  47526. _this._viewMatrix = new BABYLON.Matrix();
  47527. // Panning
  47528. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47529. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47530. _this.checkCollisions = false;
  47531. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47532. _this._previousPosition = BABYLON.Vector3.Zero();
  47533. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47534. _this._newPosition = BABYLON.Vector3.Zero();
  47535. _this._computationVector = BABYLON.Vector3.Zero();
  47536. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47537. if (collidedMesh === void 0) { collidedMesh = null; }
  47538. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47539. newPosition.multiplyInPlace(_this._collider._radius);
  47540. }
  47541. if (!collidedMesh) {
  47542. _this._previousPosition.copyFrom(_this.position);
  47543. }
  47544. else {
  47545. _this.setPosition(newPosition);
  47546. if (_this.onCollide) {
  47547. _this.onCollide(collidedMesh);
  47548. }
  47549. }
  47550. // Recompute because of constraints
  47551. var cosa = Math.cos(_this.alpha);
  47552. var sina = Math.sin(_this.alpha);
  47553. var cosb = Math.cos(_this.beta);
  47554. var sinb = Math.sin(_this.beta);
  47555. if (sinb === 0) {
  47556. sinb = 0.0001;
  47557. }
  47558. var target = _this._getTargetPosition();
  47559. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47560. target.addToRef(_this._computationVector, _this._newPosition);
  47561. _this.position.copyFrom(_this._newPosition);
  47562. var up = _this.upVector;
  47563. if (_this.allowUpsideDown && _this.beta < 0) {
  47564. up = up.clone();
  47565. up = up.negate();
  47566. }
  47567. _this._computeViewMatrix(_this.position, target, up);
  47568. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47569. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47570. _this._collisionTriggered = false;
  47571. };
  47572. _this._target = BABYLON.Vector3.Zero();
  47573. if (target) {
  47574. _this.setTarget(target);
  47575. }
  47576. _this.alpha = alpha;
  47577. _this.beta = beta;
  47578. _this.radius = radius;
  47579. _this.getViewMatrix();
  47580. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47581. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47582. return _this;
  47583. }
  47584. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47585. get: function () {
  47586. return this._target;
  47587. },
  47588. set: function (value) {
  47589. this.setTarget(value);
  47590. },
  47591. enumerable: true,
  47592. configurable: true
  47593. });
  47594. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47595. //-- begin properties for backward compatibility for inputs
  47596. get: function () {
  47597. var pointers = this.inputs.attached["pointers"];
  47598. if (pointers)
  47599. return pointers.angularSensibilityX;
  47600. return 0;
  47601. },
  47602. set: function (value) {
  47603. var pointers = this.inputs.attached["pointers"];
  47604. if (pointers) {
  47605. pointers.angularSensibilityX = value;
  47606. }
  47607. },
  47608. enumerable: true,
  47609. configurable: true
  47610. });
  47611. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47612. get: function () {
  47613. var pointers = this.inputs.attached["pointers"];
  47614. if (pointers)
  47615. return pointers.angularSensibilityY;
  47616. return 0;
  47617. },
  47618. set: function (value) {
  47619. var pointers = this.inputs.attached["pointers"];
  47620. if (pointers) {
  47621. pointers.angularSensibilityY = value;
  47622. }
  47623. },
  47624. enumerable: true,
  47625. configurable: true
  47626. });
  47627. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47628. get: function () {
  47629. var pointers = this.inputs.attached["pointers"];
  47630. if (pointers)
  47631. return pointers.pinchPrecision;
  47632. return 0;
  47633. },
  47634. set: function (value) {
  47635. var pointers = this.inputs.attached["pointers"];
  47636. if (pointers) {
  47637. pointers.pinchPrecision = value;
  47638. }
  47639. },
  47640. enumerable: true,
  47641. configurable: true
  47642. });
  47643. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47644. get: function () {
  47645. var pointers = this.inputs.attached["pointers"];
  47646. if (pointers)
  47647. return pointers.pinchDeltaPercentage;
  47648. return 0;
  47649. },
  47650. set: function (value) {
  47651. var pointers = this.inputs.attached["pointers"];
  47652. if (pointers) {
  47653. pointers.pinchDeltaPercentage = value;
  47654. }
  47655. },
  47656. enumerable: true,
  47657. configurable: true
  47658. });
  47659. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47660. get: function () {
  47661. var pointers = this.inputs.attached["pointers"];
  47662. if (pointers)
  47663. return pointers.panningSensibility;
  47664. return 0;
  47665. },
  47666. set: function (value) {
  47667. var pointers = this.inputs.attached["pointers"];
  47668. if (pointers) {
  47669. pointers.panningSensibility = value;
  47670. }
  47671. },
  47672. enumerable: true,
  47673. configurable: true
  47674. });
  47675. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47676. get: function () {
  47677. var keyboard = this.inputs.attached["keyboard"];
  47678. if (keyboard)
  47679. return keyboard.keysUp;
  47680. return [];
  47681. },
  47682. set: function (value) {
  47683. var keyboard = this.inputs.attached["keyboard"];
  47684. if (keyboard)
  47685. keyboard.keysUp = value;
  47686. },
  47687. enumerable: true,
  47688. configurable: true
  47689. });
  47690. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47691. get: function () {
  47692. var keyboard = this.inputs.attached["keyboard"];
  47693. if (keyboard)
  47694. return keyboard.keysDown;
  47695. return [];
  47696. },
  47697. set: function (value) {
  47698. var keyboard = this.inputs.attached["keyboard"];
  47699. if (keyboard)
  47700. keyboard.keysDown = value;
  47701. },
  47702. enumerable: true,
  47703. configurable: true
  47704. });
  47705. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47706. get: function () {
  47707. var keyboard = this.inputs.attached["keyboard"];
  47708. if (keyboard)
  47709. return keyboard.keysLeft;
  47710. return [];
  47711. },
  47712. set: function (value) {
  47713. var keyboard = this.inputs.attached["keyboard"];
  47714. if (keyboard)
  47715. keyboard.keysLeft = value;
  47716. },
  47717. enumerable: true,
  47718. configurable: true
  47719. });
  47720. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47721. get: function () {
  47722. var keyboard = this.inputs.attached["keyboard"];
  47723. if (keyboard)
  47724. return keyboard.keysRight;
  47725. return [];
  47726. },
  47727. set: function (value) {
  47728. var keyboard = this.inputs.attached["keyboard"];
  47729. if (keyboard)
  47730. keyboard.keysRight = value;
  47731. },
  47732. enumerable: true,
  47733. configurable: true
  47734. });
  47735. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47736. get: function () {
  47737. var mousewheel = this.inputs.attached["mousewheel"];
  47738. if (mousewheel)
  47739. return mousewheel.wheelPrecision;
  47740. return 0;
  47741. },
  47742. set: function (value) {
  47743. var mousewheel = this.inputs.attached["mousewheel"];
  47744. if (mousewheel)
  47745. mousewheel.wheelPrecision = value;
  47746. },
  47747. enumerable: true,
  47748. configurable: true
  47749. });
  47750. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47751. get: function () {
  47752. var mousewheel = this.inputs.attached["mousewheel"];
  47753. if (mousewheel)
  47754. return mousewheel.wheelDeltaPercentage;
  47755. return 0;
  47756. },
  47757. set: function (value) {
  47758. var mousewheel = this.inputs.attached["mousewheel"];
  47759. if (mousewheel)
  47760. mousewheel.wheelDeltaPercentage = value;
  47761. },
  47762. enumerable: true,
  47763. configurable: true
  47764. });
  47765. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47766. get: function () {
  47767. return this._bouncingBehavior;
  47768. },
  47769. enumerable: true,
  47770. configurable: true
  47771. });
  47772. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47773. get: function () {
  47774. return this._bouncingBehavior != null;
  47775. },
  47776. set: function (value) {
  47777. if (value === this.useBouncingBehavior) {
  47778. return;
  47779. }
  47780. if (value) {
  47781. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47782. this.addBehavior(this._bouncingBehavior);
  47783. }
  47784. else if (this._bouncingBehavior) {
  47785. this.removeBehavior(this._bouncingBehavior);
  47786. this._bouncingBehavior = null;
  47787. }
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47793. get: function () {
  47794. return this._framingBehavior;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47800. get: function () {
  47801. return this._framingBehavior != null;
  47802. },
  47803. set: function (value) {
  47804. if (value === this.useFramingBehavior) {
  47805. return;
  47806. }
  47807. if (value) {
  47808. this._framingBehavior = new BABYLON.FramingBehavior();
  47809. this.addBehavior(this._framingBehavior);
  47810. }
  47811. else if (this._framingBehavior) {
  47812. this.removeBehavior(this._framingBehavior);
  47813. this._framingBehavior = null;
  47814. }
  47815. },
  47816. enumerable: true,
  47817. configurable: true
  47818. });
  47819. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47820. get: function () {
  47821. return this._autoRotationBehavior;
  47822. },
  47823. enumerable: true,
  47824. configurable: true
  47825. });
  47826. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47827. get: function () {
  47828. return this._autoRotationBehavior != null;
  47829. },
  47830. set: function (value) {
  47831. if (value === this.useAutoRotationBehavior) {
  47832. return;
  47833. }
  47834. if (value) {
  47835. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47836. this.addBehavior(this._autoRotationBehavior);
  47837. }
  47838. else if (this._autoRotationBehavior) {
  47839. this.removeBehavior(this._autoRotationBehavior);
  47840. this._autoRotationBehavior = null;
  47841. }
  47842. },
  47843. enumerable: true,
  47844. configurable: true
  47845. });
  47846. // Cache
  47847. ArcRotateCamera.prototype._initCache = function () {
  47848. _super.prototype._initCache.call(this);
  47849. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47850. this._cache.alpha = undefined;
  47851. this._cache.beta = undefined;
  47852. this._cache.radius = undefined;
  47853. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47854. };
  47855. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47856. if (!ignoreParentClass) {
  47857. _super.prototype._updateCache.call(this);
  47858. }
  47859. this._cache._target.copyFrom(this._getTargetPosition());
  47860. this._cache.alpha = this.alpha;
  47861. this._cache.beta = this.beta;
  47862. this._cache.radius = this.radius;
  47863. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47864. };
  47865. ArcRotateCamera.prototype._getTargetPosition = function () {
  47866. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47867. var pos = this._targetHost.getAbsolutePosition();
  47868. if (this._targetBoundingCenter) {
  47869. pos.addToRef(this._targetBoundingCenter, this._target);
  47870. }
  47871. else {
  47872. this._target.copyFrom(pos);
  47873. }
  47874. }
  47875. var lockedTargetPosition = this._getLockedTargetPosition();
  47876. if (lockedTargetPosition) {
  47877. return lockedTargetPosition;
  47878. }
  47879. return this._target;
  47880. };
  47881. ArcRotateCamera.prototype.storeState = function () {
  47882. this._storedAlpha = this.alpha;
  47883. this._storedBeta = this.beta;
  47884. this._storedRadius = this.radius;
  47885. this._storedTarget = this._getTargetPosition().clone();
  47886. return _super.prototype.storeState.call(this);
  47887. };
  47888. /**
  47889. * Restored camera state. You must call storeState() first
  47890. */
  47891. ArcRotateCamera.prototype._restoreStateValues = function () {
  47892. if (!_super.prototype._restoreStateValues.call(this)) {
  47893. return false;
  47894. }
  47895. this.alpha = this._storedAlpha;
  47896. this.beta = this._storedBeta;
  47897. this.radius = this._storedRadius;
  47898. this.setTarget(this._storedTarget.clone());
  47899. this.inertialAlphaOffset = 0;
  47900. this.inertialBetaOffset = 0;
  47901. this.inertialRadiusOffset = 0;
  47902. this.inertialPanningX = 0;
  47903. this.inertialPanningY = 0;
  47904. return true;
  47905. };
  47906. // Synchronized
  47907. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47908. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47909. return false;
  47910. return this._cache._target.equals(this._getTargetPosition())
  47911. && this._cache.alpha === this.alpha
  47912. && this._cache.beta === this.beta
  47913. && this._cache.radius === this.radius
  47914. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47915. };
  47916. // Methods
  47917. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47918. var _this = this;
  47919. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47920. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47921. this._useCtrlForPanning = useCtrlForPanning;
  47922. this._panningMouseButton = panningMouseButton;
  47923. this.inputs.attachElement(element, noPreventDefault);
  47924. this._reset = function () {
  47925. _this.inertialAlphaOffset = 0;
  47926. _this.inertialBetaOffset = 0;
  47927. _this.inertialRadiusOffset = 0;
  47928. _this.inertialPanningX = 0;
  47929. _this.inertialPanningY = 0;
  47930. };
  47931. };
  47932. ArcRotateCamera.prototype.detachControl = function (element) {
  47933. this.inputs.detachElement(element);
  47934. if (this._reset) {
  47935. this._reset();
  47936. }
  47937. };
  47938. ArcRotateCamera.prototype._checkInputs = function () {
  47939. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47940. if (this._collisionTriggered) {
  47941. return;
  47942. }
  47943. this.inputs.checkInputs();
  47944. // Inertia
  47945. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47946. var inertialAlphaOffset = this.inertialAlphaOffset;
  47947. if (this.beta <= 0)
  47948. inertialAlphaOffset *= -1;
  47949. if (this.getScene().useRightHandedSystem)
  47950. inertialAlphaOffset *= -1;
  47951. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47952. inertialAlphaOffset *= -1;
  47953. this.alpha += inertialAlphaOffset;
  47954. this.beta += this.inertialBetaOffset;
  47955. this.radius -= this.inertialRadiusOffset;
  47956. this.inertialAlphaOffset *= this.inertia;
  47957. this.inertialBetaOffset *= this.inertia;
  47958. this.inertialRadiusOffset *= this.inertia;
  47959. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47960. this.inertialAlphaOffset = 0;
  47961. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47962. this.inertialBetaOffset = 0;
  47963. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47964. this.inertialRadiusOffset = 0;
  47965. }
  47966. // Panning inertia
  47967. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47968. if (!this._localDirection) {
  47969. this._localDirection = BABYLON.Vector3.Zero();
  47970. this._transformedDirection = BABYLON.Vector3.Zero();
  47971. }
  47972. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47973. this._localDirection.multiplyInPlace(this.panningAxis);
  47974. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47975. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47976. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47977. if (!this.panningAxis.y) {
  47978. this._transformedDirection.y = 0;
  47979. }
  47980. if (!this._targetHost) {
  47981. if (this.panningDistanceLimit) {
  47982. this._transformedDirection.addInPlace(this._target);
  47983. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47984. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47985. this._target.copyFrom(this._transformedDirection);
  47986. }
  47987. }
  47988. else {
  47989. this._target.addInPlace(this._transformedDirection);
  47990. }
  47991. }
  47992. this.inertialPanningX *= this.panningInertia;
  47993. this.inertialPanningY *= this.panningInertia;
  47994. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47995. this.inertialPanningX = 0;
  47996. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47997. this.inertialPanningY = 0;
  47998. }
  47999. // Limits
  48000. this._checkLimits();
  48001. _super.prototype._checkInputs.call(this);
  48002. };
  48003. ArcRotateCamera.prototype._checkLimits = function () {
  48004. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48005. if (this.allowUpsideDown && this.beta > Math.PI) {
  48006. this.beta = this.beta - (2 * Math.PI);
  48007. }
  48008. }
  48009. else {
  48010. if (this.beta < this.lowerBetaLimit) {
  48011. this.beta = this.lowerBetaLimit;
  48012. }
  48013. }
  48014. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48015. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48016. this.beta = this.beta + (2 * Math.PI);
  48017. }
  48018. }
  48019. else {
  48020. if (this.beta > this.upperBetaLimit) {
  48021. this.beta = this.upperBetaLimit;
  48022. }
  48023. }
  48024. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48025. this.alpha = this.lowerAlphaLimit;
  48026. }
  48027. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48028. this.alpha = this.upperAlphaLimit;
  48029. }
  48030. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48031. this.radius = this.lowerRadiusLimit;
  48032. }
  48033. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48034. this.radius = this.upperRadiusLimit;
  48035. }
  48036. };
  48037. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48038. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48039. this.radius = this._computationVector.length();
  48040. if (this.radius === 0) {
  48041. this.radius = 0.0001; // Just to avoid division by zero
  48042. }
  48043. // Alpha
  48044. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48045. if (this._computationVector.z < 0) {
  48046. this.alpha = 2 * Math.PI - this.alpha;
  48047. }
  48048. // Beta
  48049. this.beta = Math.acos(this._computationVector.y / this.radius);
  48050. this._checkLimits();
  48051. };
  48052. ArcRotateCamera.prototype.setPosition = function (position) {
  48053. if (this.position.equals(position)) {
  48054. return;
  48055. }
  48056. this.position.copyFrom(position);
  48057. this.rebuildAnglesAndRadius();
  48058. };
  48059. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48060. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48061. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48062. if (target.getBoundingInfo) {
  48063. if (toBoundingCenter) {
  48064. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48065. }
  48066. else {
  48067. this._targetBoundingCenter = null;
  48068. }
  48069. this._targetHost = target;
  48070. this._target = this._getTargetPosition();
  48071. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48072. }
  48073. else {
  48074. var newTarget = target;
  48075. var currentTarget = this._getTargetPosition();
  48076. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48077. return;
  48078. }
  48079. this._targetHost = null;
  48080. this._target = newTarget;
  48081. this._targetBoundingCenter = null;
  48082. this.onMeshTargetChangedObservable.notifyObservers(null);
  48083. }
  48084. this.rebuildAnglesAndRadius();
  48085. };
  48086. ArcRotateCamera.prototype._getViewMatrix = function () {
  48087. // Compute
  48088. var cosa = Math.cos(this.alpha);
  48089. var sina = Math.sin(this.alpha);
  48090. var cosb = Math.cos(this.beta);
  48091. var sinb = Math.sin(this.beta);
  48092. if (sinb === 0) {
  48093. sinb = 0.0001;
  48094. }
  48095. var target = this._getTargetPosition();
  48096. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48097. target.addToRef(this._computationVector, this._newPosition);
  48098. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48099. if (!this._collider) {
  48100. this._collider = new BABYLON.Collider();
  48101. }
  48102. this._collider._radius = this.collisionRadius;
  48103. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48104. this._collisionTriggered = true;
  48105. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48106. }
  48107. else {
  48108. this.position.copyFrom(this._newPosition);
  48109. var up = this.upVector;
  48110. if (this.allowUpsideDown && sinb < 0) {
  48111. up = up.clone();
  48112. up = up.negate();
  48113. }
  48114. this._computeViewMatrix(this.position, target, up);
  48115. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48116. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48117. }
  48118. this._currentTarget = target;
  48119. return this._viewMatrix;
  48120. };
  48121. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48122. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48123. meshes = meshes || this.getScene().meshes;
  48124. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48125. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48126. this.radius = distance * this.zoomOnFactor;
  48127. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48128. };
  48129. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48130. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48131. var meshesOrMinMaxVector;
  48132. var distance;
  48133. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48134. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48135. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48136. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48137. }
  48138. else { //minMaxVector and distance
  48139. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48140. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48141. distance = minMaxVectorAndDistance.distance;
  48142. }
  48143. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48144. if (!doNotUpdateMaxZ) {
  48145. this.maxZ = distance * 2;
  48146. }
  48147. };
  48148. /**
  48149. * @override
  48150. * Override Camera.createRigCamera
  48151. */
  48152. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48153. var alphaShift = 0;
  48154. switch (this.cameraRigMode) {
  48155. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48156. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48157. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48158. case BABYLON.Camera.RIG_MODE_VR:
  48159. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48160. break;
  48161. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48162. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48163. break;
  48164. }
  48165. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48166. rigCam._cameraRigParams = {};
  48167. return rigCam;
  48168. };
  48169. /**
  48170. * @override
  48171. * Override Camera._updateRigCameras
  48172. */
  48173. ArcRotateCamera.prototype._updateRigCameras = function () {
  48174. var camLeft = this._rigCameras[0];
  48175. var camRight = this._rigCameras[1];
  48176. camLeft.beta = camRight.beta = this.beta;
  48177. camLeft.radius = camRight.radius = this.radius;
  48178. switch (this.cameraRigMode) {
  48179. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48181. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48182. case BABYLON.Camera.RIG_MODE_VR:
  48183. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48184. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48185. break;
  48186. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48187. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48188. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48189. break;
  48190. }
  48191. _super.prototype._updateRigCameras.call(this);
  48192. };
  48193. ArcRotateCamera.prototype.dispose = function () {
  48194. this.inputs.clear();
  48195. _super.prototype.dispose.call(this);
  48196. };
  48197. ArcRotateCamera.prototype.getClassName = function () {
  48198. return "ArcRotateCamera";
  48199. };
  48200. __decorate([
  48201. BABYLON.serialize()
  48202. ], ArcRotateCamera.prototype, "alpha", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], ArcRotateCamera.prototype, "beta", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], ArcRotateCamera.prototype, "radius", void 0);
  48209. __decorate([
  48210. BABYLON.serializeAsVector3("target")
  48211. ], ArcRotateCamera.prototype, "_target", void 0);
  48212. __decorate([
  48213. BABYLON.serialize()
  48214. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48215. __decorate([
  48216. BABYLON.serialize()
  48217. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48218. __decorate([
  48219. BABYLON.serialize()
  48220. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48221. __decorate([
  48222. BABYLON.serialize()
  48223. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48224. __decorate([
  48225. BABYLON.serialize()
  48226. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48227. __decorate([
  48228. BABYLON.serialize()
  48229. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48230. __decorate([
  48231. BABYLON.serialize()
  48232. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48233. __decorate([
  48234. BABYLON.serialize()
  48235. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48236. __decorate([
  48237. BABYLON.serialize()
  48238. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48239. __decorate([
  48240. BABYLON.serialize()
  48241. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48242. __decorate([
  48243. BABYLON.serialize()
  48244. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48245. __decorate([
  48246. BABYLON.serialize()
  48247. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48248. __decorate([
  48249. BABYLON.serialize()
  48250. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48251. __decorate([
  48252. BABYLON.serializeAsVector3()
  48253. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48254. __decorate([
  48255. BABYLON.serialize()
  48256. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48257. __decorate([
  48258. BABYLON.serialize()
  48259. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48260. __decorate([
  48261. BABYLON.serialize()
  48262. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48263. return ArcRotateCamera;
  48264. }(BABYLON.TargetCamera));
  48265. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48266. })(BABYLON || (BABYLON = {}));
  48267. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48268. var BABYLON;
  48269. (function (BABYLON) {
  48270. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48271. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48272. });
  48273. /**
  48274. * The HemisphericLight simulates the ambient environment light,
  48275. * so the passed direction is the light reflection direction, not the incoming direction.
  48276. */
  48277. var HemisphericLight = /** @class */ (function (_super) {
  48278. __extends(HemisphericLight, _super);
  48279. /**
  48280. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48281. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48282. * The HemisphericLight can't cast shadows.
  48283. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48284. * @param name The friendly name of the light
  48285. * @param direction The direction of the light reflection
  48286. * @param scene The scene the light belongs to
  48287. */
  48288. function HemisphericLight(name, direction, scene) {
  48289. var _this = _super.call(this, name, scene) || this;
  48290. /**
  48291. * The groundColor is the light in the opposite direction to the one specified during creation.
  48292. * 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.
  48293. */
  48294. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48295. _this.direction = direction || BABYLON.Vector3.Up();
  48296. return _this;
  48297. }
  48298. HemisphericLight.prototype._buildUniformLayout = function () {
  48299. this._uniformBuffer.addUniform("vLightData", 4);
  48300. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48301. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48302. this._uniformBuffer.addUniform("vLightGround", 3);
  48303. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48304. this._uniformBuffer.addUniform("depthValues", 2);
  48305. this._uniformBuffer.create();
  48306. };
  48307. /**
  48308. * Returns the string "HemisphericLight".
  48309. * @return The class name
  48310. */
  48311. HemisphericLight.prototype.getClassName = function () {
  48312. return "HemisphericLight";
  48313. };
  48314. /**
  48315. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48316. * Returns the updated direction.
  48317. * @param target The target the direction should point to
  48318. * @return The computed direction
  48319. */
  48320. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48321. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48322. return this.direction;
  48323. };
  48324. /**
  48325. * Returns the shadow generator associated to the light.
  48326. * @returns Always null for hemispheric lights because it does not support shadows.
  48327. */
  48328. HemisphericLight.prototype.getShadowGenerator = function () {
  48329. return null;
  48330. };
  48331. /**
  48332. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48333. * @param effect The effect to update
  48334. * @param lightIndex The index of the light in the effect to update
  48335. * @returns The hemispheric light
  48336. */
  48337. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48338. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48339. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48340. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48341. return this;
  48342. };
  48343. /**
  48344. * @hidden internal use only.
  48345. */
  48346. HemisphericLight.prototype._getWorldMatrix = function () {
  48347. if (!this._worldMatrix) {
  48348. this._worldMatrix = BABYLON.Matrix.Identity();
  48349. }
  48350. return this._worldMatrix;
  48351. };
  48352. /**
  48353. * Returns the integer 3.
  48354. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48355. */
  48356. HemisphericLight.prototype.getTypeID = function () {
  48357. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48358. };
  48359. /**
  48360. * Prepares the list of defines specific to the light type.
  48361. * @param defines the list of defines
  48362. * @param lightIndex defines the index of the light for the effect
  48363. */
  48364. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48365. defines["HEMILIGHT" + lightIndex] = true;
  48366. };
  48367. __decorate([
  48368. BABYLON.serializeAsColor3()
  48369. ], HemisphericLight.prototype, "groundColor", void 0);
  48370. __decorate([
  48371. BABYLON.serializeAsVector3()
  48372. ], HemisphericLight.prototype, "direction", void 0);
  48373. return HemisphericLight;
  48374. }(BABYLON.Light));
  48375. BABYLON.HemisphericLight = HemisphericLight;
  48376. })(BABYLON || (BABYLON = {}));
  48377. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48378. var BABYLON;
  48379. (function (BABYLON) {
  48380. /**
  48381. * Base implementation IShadowLight
  48382. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48383. */
  48384. var ShadowLight = /** @class */ (function (_super) {
  48385. __extends(ShadowLight, _super);
  48386. function ShadowLight() {
  48387. var _this = _super !== null && _super.apply(this, arguments) || this;
  48388. _this._needProjectionMatrixCompute = true;
  48389. return _this;
  48390. }
  48391. ShadowLight.prototype._setPosition = function (value) {
  48392. this._position = value;
  48393. };
  48394. Object.defineProperty(ShadowLight.prototype, "position", {
  48395. /**
  48396. * Sets the position the shadow will be casted from. Also use as the light position for both
  48397. * point and spot lights.
  48398. */
  48399. get: function () {
  48400. return this._position;
  48401. },
  48402. /**
  48403. * Sets the position the shadow will be casted from. Also use as the light position for both
  48404. * point and spot lights.
  48405. */
  48406. set: function (value) {
  48407. this._setPosition(value);
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. ShadowLight.prototype._setDirection = function (value) {
  48413. this._direction = value;
  48414. };
  48415. Object.defineProperty(ShadowLight.prototype, "direction", {
  48416. /**
  48417. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48418. * Also use as the light direction on spot and directional lights.
  48419. */
  48420. get: function () {
  48421. return this._direction;
  48422. },
  48423. /**
  48424. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48425. * Also use as the light direction on spot and directional lights.
  48426. */
  48427. set: function (value) {
  48428. this._setDirection(value);
  48429. },
  48430. enumerable: true,
  48431. configurable: true
  48432. });
  48433. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48434. /**
  48435. * Gets the shadow projection clipping minimum z value.
  48436. */
  48437. get: function () {
  48438. return this._shadowMinZ;
  48439. },
  48440. /**
  48441. * Sets the shadow projection clipping minimum z value.
  48442. */
  48443. set: function (value) {
  48444. this._shadowMinZ = value;
  48445. this.forceProjectionMatrixCompute();
  48446. },
  48447. enumerable: true,
  48448. configurable: true
  48449. });
  48450. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48451. /**
  48452. * Sets the shadow projection clipping maximum z value.
  48453. */
  48454. get: function () {
  48455. return this._shadowMaxZ;
  48456. },
  48457. /**
  48458. * Gets the shadow projection clipping maximum z value.
  48459. */
  48460. set: function (value) {
  48461. this._shadowMaxZ = value;
  48462. this.forceProjectionMatrixCompute();
  48463. },
  48464. enumerable: true,
  48465. configurable: true
  48466. });
  48467. /**
  48468. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48469. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48470. */
  48471. ShadowLight.prototype.computeTransformedInformation = function () {
  48472. if (this.parent && this.parent.getWorldMatrix) {
  48473. if (!this.transformedPosition) {
  48474. this.transformedPosition = BABYLON.Vector3.Zero();
  48475. }
  48476. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48477. // In case the direction is present.
  48478. if (this.direction) {
  48479. if (!this.transformedDirection) {
  48480. this.transformedDirection = BABYLON.Vector3.Zero();
  48481. }
  48482. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48483. }
  48484. return true;
  48485. }
  48486. return false;
  48487. };
  48488. /**
  48489. * Return the depth scale used for the shadow map.
  48490. * @returns the depth scale.
  48491. */
  48492. ShadowLight.prototype.getDepthScale = function () {
  48493. return 50.0;
  48494. };
  48495. /**
  48496. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48497. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48498. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48499. */
  48500. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48501. return this.transformedDirection ? this.transformedDirection : this.direction;
  48502. };
  48503. /**
  48504. * Returns the ShadowLight absolute position in the World.
  48505. * @returns the position vector in world space
  48506. */
  48507. ShadowLight.prototype.getAbsolutePosition = function () {
  48508. return this.transformedPosition ? this.transformedPosition : this.position;
  48509. };
  48510. /**
  48511. * Sets the ShadowLight direction toward the passed target.
  48512. * @param target The point tot target in local space
  48513. * @returns the updated ShadowLight direction
  48514. */
  48515. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48516. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48517. return this.direction;
  48518. };
  48519. /**
  48520. * Returns the light rotation in euler definition.
  48521. * @returns the x y z rotation in local space.
  48522. */
  48523. ShadowLight.prototype.getRotation = function () {
  48524. this.direction.normalize();
  48525. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48526. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48527. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48528. };
  48529. /**
  48530. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48531. * @returns true if a cube texture needs to be use
  48532. */
  48533. ShadowLight.prototype.needCube = function () {
  48534. return false;
  48535. };
  48536. /**
  48537. * Detects if the projection matrix requires to be recomputed this frame.
  48538. * @returns true if it requires to be recomputed otherwise, false.
  48539. */
  48540. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48541. return this._needProjectionMatrixCompute;
  48542. };
  48543. /**
  48544. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48545. */
  48546. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48547. this._needProjectionMatrixCompute = true;
  48548. };
  48549. /**
  48550. * Get the world matrix of the sahdow lights.
  48551. * @hidden Internal Use Only
  48552. */
  48553. ShadowLight.prototype._getWorldMatrix = function () {
  48554. if (!this._worldMatrix) {
  48555. this._worldMatrix = BABYLON.Matrix.Identity();
  48556. }
  48557. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48558. return this._worldMatrix;
  48559. };
  48560. /**
  48561. * Gets the minZ used for shadow according to both the scene and the light.
  48562. * @param activeCamera The camera we are returning the min for
  48563. * @returns the depth min z
  48564. */
  48565. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48566. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48567. };
  48568. /**
  48569. * Gets the maxZ used for shadow according to both the scene and the light.
  48570. * @param activeCamera The camera we are returning the max for
  48571. * @returns the depth max z
  48572. */
  48573. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48574. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48575. };
  48576. /**
  48577. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48578. * @param matrix The materix to updated with the projection information
  48579. * @param viewMatrix The transform matrix of the light
  48580. * @param renderList The list of mesh to render in the map
  48581. * @returns The current light
  48582. */
  48583. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48584. if (this.customProjectionMatrixBuilder) {
  48585. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48586. }
  48587. else {
  48588. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48589. }
  48590. return this;
  48591. };
  48592. __decorate([
  48593. BABYLON.serializeAsVector3()
  48594. ], ShadowLight.prototype, "position", null);
  48595. __decorate([
  48596. BABYLON.serializeAsVector3()
  48597. ], ShadowLight.prototype, "direction", null);
  48598. __decorate([
  48599. BABYLON.serialize()
  48600. ], ShadowLight.prototype, "shadowMinZ", null);
  48601. __decorate([
  48602. BABYLON.serialize()
  48603. ], ShadowLight.prototype, "shadowMaxZ", null);
  48604. return ShadowLight;
  48605. }(BABYLON.Light));
  48606. BABYLON.ShadowLight = ShadowLight;
  48607. })(BABYLON || (BABYLON = {}));
  48608. //# sourceMappingURL=babylon.shadowLight.js.map
  48609. var BABYLON;
  48610. (function (BABYLON) {
  48611. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48612. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48613. });
  48614. /**
  48615. * A point light is a light defined by an unique point in world space.
  48616. * The light is emitted in every direction from this point.
  48617. * A good example of a point light is a standard light bulb.
  48618. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48619. */
  48620. var PointLight = /** @class */ (function (_super) {
  48621. __extends(PointLight, _super);
  48622. /**
  48623. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48624. * A PointLight emits the light in every direction.
  48625. * It can cast shadows.
  48626. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48627. * ```javascript
  48628. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48629. * ```
  48630. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48631. * @param name The light friendly name
  48632. * @param position The position of the point light in the scene
  48633. * @param scene The scene the lights belongs to
  48634. */
  48635. function PointLight(name, position, scene) {
  48636. var _this = _super.call(this, name, scene) || this;
  48637. _this._shadowAngle = Math.PI / 2;
  48638. _this.position = position;
  48639. return _this;
  48640. }
  48641. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48642. /**
  48643. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48644. * This specifies what angle the shadow will use to be created.
  48645. *
  48646. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48647. */
  48648. get: function () {
  48649. return this._shadowAngle;
  48650. },
  48651. /**
  48652. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48653. * This specifies what angle the shadow will use to be created.
  48654. *
  48655. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48656. */
  48657. set: function (value) {
  48658. this._shadowAngle = value;
  48659. this.forceProjectionMatrixCompute();
  48660. },
  48661. enumerable: true,
  48662. configurable: true
  48663. });
  48664. Object.defineProperty(PointLight.prototype, "direction", {
  48665. /**
  48666. * Gets the direction if it has been set.
  48667. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48668. */
  48669. get: function () {
  48670. return this._direction;
  48671. },
  48672. /**
  48673. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48674. */
  48675. set: function (value) {
  48676. var previousNeedCube = this.needCube();
  48677. this._direction = value;
  48678. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48679. this._shadowGenerator.recreateShadowMap();
  48680. }
  48681. },
  48682. enumerable: true,
  48683. configurable: true
  48684. });
  48685. /**
  48686. * Returns the string "PointLight"
  48687. * @returns the class name
  48688. */
  48689. PointLight.prototype.getClassName = function () {
  48690. return "PointLight";
  48691. };
  48692. /**
  48693. * Returns the integer 0.
  48694. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48695. */
  48696. PointLight.prototype.getTypeID = function () {
  48697. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48698. };
  48699. /**
  48700. * Specifies wether or not the shadowmap should be a cube texture.
  48701. * @returns true if the shadowmap needs to be a cube texture.
  48702. */
  48703. PointLight.prototype.needCube = function () {
  48704. return !this.direction;
  48705. };
  48706. /**
  48707. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48708. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48709. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48710. */
  48711. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48712. if (this.direction) {
  48713. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48714. }
  48715. else {
  48716. switch (faceIndex) {
  48717. case 0:
  48718. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48719. case 1:
  48720. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48721. case 2:
  48722. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48723. case 3:
  48724. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48725. case 4:
  48726. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48727. case 5:
  48728. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48729. }
  48730. }
  48731. return BABYLON.Vector3.Zero();
  48732. };
  48733. /**
  48734. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48735. * - fov = PI / 2
  48736. * - aspect ratio : 1.0
  48737. * - z-near and far equal to the active camera minZ and maxZ.
  48738. * Returns the PointLight.
  48739. */
  48740. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48741. var activeCamera = this.getScene().activeCamera;
  48742. if (!activeCamera) {
  48743. return;
  48744. }
  48745. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48746. };
  48747. PointLight.prototype._buildUniformLayout = function () {
  48748. this._uniformBuffer.addUniform("vLightData", 4);
  48749. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48750. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48751. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48752. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48753. this._uniformBuffer.addUniform("depthValues", 2);
  48754. this._uniformBuffer.create();
  48755. };
  48756. /**
  48757. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48758. * @param effect The effect to update
  48759. * @param lightIndex The index of the light in the effect to update
  48760. * @returns The point light
  48761. */
  48762. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48763. if (this.computeTransformedInformation()) {
  48764. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48765. }
  48766. else {
  48767. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48768. }
  48769. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48770. return this;
  48771. };
  48772. /**
  48773. * Prepares the list of defines specific to the light type.
  48774. * @param defines the list of defines
  48775. * @param lightIndex defines the index of the light for the effect
  48776. */
  48777. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48778. defines["POINTLIGHT" + lightIndex] = true;
  48779. };
  48780. __decorate([
  48781. BABYLON.serialize()
  48782. ], PointLight.prototype, "shadowAngle", null);
  48783. return PointLight;
  48784. }(BABYLON.ShadowLight));
  48785. BABYLON.PointLight = PointLight;
  48786. })(BABYLON || (BABYLON = {}));
  48787. //# sourceMappingURL=babylon.pointLight.js.map
  48788. var BABYLON;
  48789. (function (BABYLON) {
  48790. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48791. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48792. });
  48793. /**
  48794. * A directional light is defined by a direction (what a surprise!).
  48795. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48796. * 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.
  48797. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48798. */
  48799. var DirectionalLight = /** @class */ (function (_super) {
  48800. __extends(DirectionalLight, _super);
  48801. /**
  48802. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48803. * The directional light is emitted from everywhere in the given direction.
  48804. * It can cast shawdows.
  48805. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48806. * @param name The friendly name of the light
  48807. * @param direction The direction of the light
  48808. * @param scene The scene the light belongs to
  48809. */
  48810. function DirectionalLight(name, direction, scene) {
  48811. var _this = _super.call(this, name, scene) || this;
  48812. _this._shadowFrustumSize = 0;
  48813. _this._shadowOrthoScale = 0.1;
  48814. /**
  48815. * Automatically compute the projection matrix to best fit (including all the casters)
  48816. * on each frame.
  48817. */
  48818. _this.autoUpdateExtends = true;
  48819. // Cache
  48820. _this._orthoLeft = Number.MAX_VALUE;
  48821. _this._orthoRight = Number.MIN_VALUE;
  48822. _this._orthoTop = Number.MIN_VALUE;
  48823. _this._orthoBottom = Number.MAX_VALUE;
  48824. _this.position = direction.scale(-1.0);
  48825. _this.direction = direction;
  48826. return _this;
  48827. }
  48828. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48829. /**
  48830. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48831. */
  48832. get: function () {
  48833. return this._shadowFrustumSize;
  48834. },
  48835. /**
  48836. * Specifies a fix frustum size for the shadow generation.
  48837. */
  48838. set: function (value) {
  48839. this._shadowFrustumSize = value;
  48840. this.forceProjectionMatrixCompute();
  48841. },
  48842. enumerable: true,
  48843. configurable: true
  48844. });
  48845. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48846. /**
  48847. * Gets the shadow projection scale against the optimal computed one.
  48848. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48849. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48850. */
  48851. get: function () {
  48852. return this._shadowOrthoScale;
  48853. },
  48854. /**
  48855. * Sets the shadow projection scale against the optimal computed one.
  48856. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48857. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48858. */
  48859. set: function (value) {
  48860. this._shadowOrthoScale = value;
  48861. this.forceProjectionMatrixCompute();
  48862. },
  48863. enumerable: true,
  48864. configurable: true
  48865. });
  48866. /**
  48867. * Returns the string "DirectionalLight".
  48868. * @return The class name
  48869. */
  48870. DirectionalLight.prototype.getClassName = function () {
  48871. return "DirectionalLight";
  48872. };
  48873. /**
  48874. * Returns the integer 1.
  48875. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48876. */
  48877. DirectionalLight.prototype.getTypeID = function () {
  48878. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48879. };
  48880. /**
  48881. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48882. * Returns the DirectionalLight Shadow projection matrix.
  48883. */
  48884. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48885. if (this.shadowFrustumSize > 0) {
  48886. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48887. }
  48888. else {
  48889. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48890. }
  48891. };
  48892. /**
  48893. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48894. * Returns the DirectionalLight Shadow projection matrix.
  48895. */
  48896. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48897. var activeCamera = this.getScene().activeCamera;
  48898. if (!activeCamera) {
  48899. return;
  48900. }
  48901. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48902. };
  48903. /**
  48904. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48905. * Returns the DirectionalLight Shadow projection matrix.
  48906. */
  48907. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48908. var activeCamera = this.getScene().activeCamera;
  48909. if (!activeCamera) {
  48910. return;
  48911. }
  48912. // Check extends
  48913. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48914. var tempVector3 = BABYLON.Vector3.Zero();
  48915. this._orthoLeft = Number.MAX_VALUE;
  48916. this._orthoRight = Number.MIN_VALUE;
  48917. this._orthoTop = Number.MIN_VALUE;
  48918. this._orthoBottom = Number.MAX_VALUE;
  48919. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48920. var mesh = renderList[meshIndex];
  48921. if (!mesh) {
  48922. continue;
  48923. }
  48924. var boundingInfo = mesh.getBoundingInfo();
  48925. var boundingBox = boundingInfo.boundingBox;
  48926. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48927. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48928. if (tempVector3.x < this._orthoLeft)
  48929. this._orthoLeft = tempVector3.x;
  48930. if (tempVector3.y < this._orthoBottom)
  48931. this._orthoBottom = tempVector3.y;
  48932. if (tempVector3.x > this._orthoRight)
  48933. this._orthoRight = tempVector3.x;
  48934. if (tempVector3.y > this._orthoTop)
  48935. this._orthoTop = tempVector3.y;
  48936. }
  48937. }
  48938. }
  48939. var xOffset = this._orthoRight - this._orthoLeft;
  48940. var yOffset = this._orthoTop - this._orthoBottom;
  48941. 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);
  48942. };
  48943. DirectionalLight.prototype._buildUniformLayout = function () {
  48944. this._uniformBuffer.addUniform("vLightData", 4);
  48945. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48946. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48947. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48948. this._uniformBuffer.addUniform("depthValues", 2);
  48949. this._uniformBuffer.create();
  48950. };
  48951. /**
  48952. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48953. * @param effect The effect to update
  48954. * @param lightIndex The index of the light in the effect to update
  48955. * @returns The directional light
  48956. */
  48957. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48958. if (this.computeTransformedInformation()) {
  48959. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48960. return this;
  48961. }
  48962. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48963. return this;
  48964. };
  48965. /**
  48966. * Gets the minZ used for shadow according to both the scene and the light.
  48967. *
  48968. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48969. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48970. * @param activeCamera The camera we are returning the min for
  48971. * @returns the depth min z
  48972. */
  48973. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48974. return 1;
  48975. };
  48976. /**
  48977. * Gets the maxZ used for shadow according to both the scene and the light.
  48978. *
  48979. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48980. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48981. * @param activeCamera The camera we are returning the max for
  48982. * @returns the depth max z
  48983. */
  48984. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48985. return 1;
  48986. };
  48987. /**
  48988. * Prepares the list of defines specific to the light type.
  48989. * @param defines the list of defines
  48990. * @param lightIndex defines the index of the light for the effect
  48991. */
  48992. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48993. defines["DIRLIGHT" + lightIndex] = true;
  48994. };
  48995. __decorate([
  48996. BABYLON.serialize()
  48997. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48998. __decorate([
  48999. BABYLON.serialize()
  49000. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49001. __decorate([
  49002. BABYLON.serialize()
  49003. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49004. return DirectionalLight;
  49005. }(BABYLON.ShadowLight));
  49006. BABYLON.DirectionalLight = DirectionalLight;
  49007. })(BABYLON || (BABYLON = {}));
  49008. //# sourceMappingURL=babylon.directionalLight.js.map
  49009. var BABYLON;
  49010. (function (BABYLON) {
  49011. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49012. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49013. });
  49014. /**
  49015. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49016. * These values define a cone of light starting from the position, emitting toward the direction.
  49017. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49018. * and the exponent defines the speed of the decay of the light with distance (reach).
  49019. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49020. */
  49021. var SpotLight = /** @class */ (function (_super) {
  49022. __extends(SpotLight, _super);
  49023. /**
  49024. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49025. * It can cast shadows.
  49026. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49027. * @param name The light friendly name
  49028. * @param position The position of the spot light in the scene
  49029. * @param direction The direction of the light in the scene
  49030. * @param angle The cone angle of the light in Radians
  49031. * @param exponent The light decay speed with the distance from the emission spot
  49032. * @param scene The scene the lights belongs to
  49033. */
  49034. function SpotLight(name, position, direction, angle, exponent, scene) {
  49035. var _this = _super.call(this, name, scene) || this;
  49036. _this._innerAngle = 0;
  49037. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49038. _this._projectionTextureLightNear = 1e-6;
  49039. _this._projectionTextureLightFar = 1000.0;
  49040. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49041. _this._projectionTextureViewLightDirty = true;
  49042. _this._projectionTextureProjectionLightDirty = true;
  49043. _this._projectionTextureDirty = true;
  49044. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49045. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49046. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49047. _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);
  49048. _this.position = position;
  49049. _this.direction = direction;
  49050. _this.angle = angle;
  49051. _this.exponent = exponent;
  49052. return _this;
  49053. }
  49054. Object.defineProperty(SpotLight.prototype, "angle", {
  49055. /**
  49056. * Gets the cone angle of the spot light in Radians.
  49057. */
  49058. get: function () {
  49059. return this._angle;
  49060. },
  49061. /**
  49062. * Sets the cone angle of the spot light in Radians.
  49063. */
  49064. set: function (value) {
  49065. this._angle = value;
  49066. this._cosHalfAngle = Math.cos(value * 0.5);
  49067. this._projectionTextureProjectionLightDirty = true;
  49068. this.forceProjectionMatrixCompute();
  49069. this._computeAngleValues();
  49070. },
  49071. enumerable: true,
  49072. configurable: true
  49073. });
  49074. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49075. /**
  49076. * Only used in gltf falloff mode, this defines the angle where
  49077. * the directional falloff will start before cutting at angle which could be seen
  49078. * as outer angle.
  49079. */
  49080. get: function () {
  49081. return this._angle;
  49082. },
  49083. /**
  49084. * Only used in gltf falloff mode, this defines the angle where
  49085. * the directional falloff will start before cutting at angle which could be seen
  49086. * as outer angle.
  49087. */
  49088. set: function (value) {
  49089. this._innerAngle = value;
  49090. this._computeAngleValues();
  49091. },
  49092. enumerable: true,
  49093. configurable: true
  49094. });
  49095. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49096. /**
  49097. * Allows scaling the angle of the light for shadow generation only.
  49098. */
  49099. get: function () {
  49100. return this._shadowAngleScale;
  49101. },
  49102. /**
  49103. * Allows scaling the angle of the light for shadow generation only.
  49104. */
  49105. set: function (value) {
  49106. this._shadowAngleScale = value;
  49107. this.forceProjectionMatrixCompute();
  49108. },
  49109. enumerable: true,
  49110. configurable: true
  49111. });
  49112. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49113. /**
  49114. * Allows reading the projecton texture
  49115. */
  49116. get: function () {
  49117. return this._projectionTextureMatrix;
  49118. },
  49119. enumerable: true,
  49120. configurable: true
  49121. });
  49122. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49123. /**
  49124. * Gets the near clip of the Spotlight for texture projection.
  49125. */
  49126. get: function () {
  49127. return this._projectionTextureLightNear;
  49128. },
  49129. /**
  49130. * Sets the near clip of the Spotlight for texture projection.
  49131. */
  49132. set: function (value) {
  49133. this._projectionTextureLightNear = value;
  49134. this._projectionTextureProjectionLightDirty = true;
  49135. },
  49136. enumerable: true,
  49137. configurable: true
  49138. });
  49139. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49140. /**
  49141. * Gets the far clip of the Spotlight for texture projection.
  49142. */
  49143. get: function () {
  49144. return this._projectionTextureLightFar;
  49145. },
  49146. /**
  49147. * Sets the far clip of the Spotlight for texture projection.
  49148. */
  49149. set: function (value) {
  49150. this._projectionTextureLightFar = value;
  49151. this._projectionTextureProjectionLightDirty = true;
  49152. },
  49153. enumerable: true,
  49154. configurable: true
  49155. });
  49156. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49157. /**
  49158. * Gets the Up vector of the Spotlight for texture projection.
  49159. */
  49160. get: function () {
  49161. return this._projectionTextureUpDirection;
  49162. },
  49163. /**
  49164. * Sets the Up vector of the Spotlight for texture projection.
  49165. */
  49166. set: function (value) {
  49167. this._projectionTextureUpDirection = value;
  49168. this._projectionTextureProjectionLightDirty = true;
  49169. },
  49170. enumerable: true,
  49171. configurable: true
  49172. });
  49173. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49174. /**
  49175. * Gets the projection texture of the light.
  49176. */
  49177. get: function () {
  49178. return this._projectionTexture;
  49179. },
  49180. /**
  49181. * Sets the projection texture of the light.
  49182. */
  49183. set: function (value) {
  49184. this._projectionTexture = value;
  49185. this._projectionTextureDirty = true;
  49186. },
  49187. enumerable: true,
  49188. configurable: true
  49189. });
  49190. /**
  49191. * Returns the string "SpotLight".
  49192. * @returns the class name
  49193. */
  49194. SpotLight.prototype.getClassName = function () {
  49195. return "SpotLight";
  49196. };
  49197. /**
  49198. * Returns the integer 2.
  49199. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49200. */
  49201. SpotLight.prototype.getTypeID = function () {
  49202. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49203. };
  49204. /**
  49205. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49206. */
  49207. SpotLight.prototype._setDirection = function (value) {
  49208. _super.prototype._setDirection.call(this, value);
  49209. this._projectionTextureViewLightDirty = true;
  49210. };
  49211. /**
  49212. * Overrides the position setter to recompute the projection texture view light Matrix.
  49213. */
  49214. SpotLight.prototype._setPosition = function (value) {
  49215. _super.prototype._setPosition.call(this, value);
  49216. this._projectionTextureViewLightDirty = true;
  49217. };
  49218. /**
  49219. * 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.
  49220. * Returns the SpotLight.
  49221. */
  49222. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49223. var activeCamera = this.getScene().activeCamera;
  49224. if (!activeCamera) {
  49225. return;
  49226. }
  49227. this._shadowAngleScale = this._shadowAngleScale || 1;
  49228. var angle = this._shadowAngleScale * this._angle;
  49229. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49230. };
  49231. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49232. this._projectionTextureViewLightDirty = false;
  49233. this._projectionTextureDirty = true;
  49234. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49235. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49236. };
  49237. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49238. this._projectionTextureProjectionLightDirty = false;
  49239. this._projectionTextureDirty = true;
  49240. var light_far = this.projectionTextureLightFar;
  49241. var light_near = this.projectionTextureLightNear;
  49242. var P = light_far / (light_far - light_near);
  49243. var Q = -P * light_near;
  49244. var S = 1.0 / Math.tan(this._angle / 2.0);
  49245. var A = 1.0;
  49246. 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);
  49247. };
  49248. /**
  49249. * Main function for light texture projection matrix computing.
  49250. */
  49251. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49252. this._projectionTextureDirty = false;
  49253. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49254. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49255. };
  49256. SpotLight.prototype._buildUniformLayout = function () {
  49257. this._uniformBuffer.addUniform("vLightData", 4);
  49258. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49259. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49260. this._uniformBuffer.addUniform("vLightDirection", 3);
  49261. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49262. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49263. this._uniformBuffer.addUniform("depthValues", 2);
  49264. this._uniformBuffer.create();
  49265. };
  49266. SpotLight.prototype._computeAngleValues = function () {
  49267. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49268. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49269. };
  49270. /**
  49271. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49272. * @param effect The effect to update
  49273. * @param lightIndex The index of the light in the effect to update
  49274. * @returns The spot light
  49275. */
  49276. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49277. var normalizeDirection;
  49278. if (this.computeTransformedInformation()) {
  49279. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49280. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49281. }
  49282. else {
  49283. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49284. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49285. }
  49286. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49287. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49288. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49289. if (this._projectionTextureViewLightDirty) {
  49290. this._computeProjectionTextureViewLightMatrix();
  49291. }
  49292. if (this._projectionTextureProjectionLightDirty) {
  49293. this._computeProjectionTextureProjectionLightMatrix();
  49294. }
  49295. if (this._projectionTextureDirty) {
  49296. this._computeProjectionTextureMatrix();
  49297. }
  49298. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49299. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49300. }
  49301. return this;
  49302. };
  49303. /**
  49304. * Disposes the light and the associated resources.
  49305. */
  49306. SpotLight.prototype.dispose = function () {
  49307. _super.prototype.dispose.call(this);
  49308. if (this._projectionTexture) {
  49309. this._projectionTexture.dispose();
  49310. }
  49311. };
  49312. /**
  49313. * Prepares the list of defines specific to the light type.
  49314. * @param defines the list of defines
  49315. * @param lightIndex defines the index of the light for the effect
  49316. */
  49317. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49318. defines["SPOTLIGHT" + lightIndex] = true;
  49319. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49320. };
  49321. __decorate([
  49322. BABYLON.serialize()
  49323. ], SpotLight.prototype, "angle", null);
  49324. __decorate([
  49325. BABYLON.serialize()
  49326. ], SpotLight.prototype, "innerAngle", null);
  49327. __decorate([
  49328. BABYLON.serialize()
  49329. ], SpotLight.prototype, "shadowAngleScale", null);
  49330. __decorate([
  49331. BABYLON.serialize()
  49332. ], SpotLight.prototype, "exponent", void 0);
  49333. __decorate([
  49334. BABYLON.serialize()
  49335. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49336. __decorate([
  49337. BABYLON.serialize()
  49338. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49339. __decorate([
  49340. BABYLON.serialize()
  49341. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49342. __decorate([
  49343. BABYLON.serializeAsTexture("projectedLightTexture")
  49344. ], SpotLight.prototype, "_projectionTexture", void 0);
  49345. return SpotLight;
  49346. }(BABYLON.ShadowLight));
  49347. BABYLON.SpotLight = SpotLight;
  49348. })(BABYLON || (BABYLON = {}));
  49349. //# sourceMappingURL=babylon.spotLight.js.map
  49350. var BABYLON;
  49351. (function (BABYLON) {
  49352. /**
  49353. * Class used to override all child animations of a given target
  49354. */
  49355. var AnimationPropertiesOverride = /** @class */ (function () {
  49356. function AnimationPropertiesOverride() {
  49357. /**
  49358. * Gets or sets a value indicating if animation blending must be used
  49359. */
  49360. this.enableBlending = false;
  49361. /**
  49362. * Gets or sets the blending speed to use when enableBlending is true
  49363. */
  49364. this.blendingSpeed = 0.01;
  49365. /**
  49366. * Gets or sets the default loop mode to use
  49367. */
  49368. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49369. }
  49370. return AnimationPropertiesOverride;
  49371. }());
  49372. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49373. })(BABYLON || (BABYLON = {}));
  49374. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49375. var BABYLON;
  49376. (function (BABYLON) {
  49377. /**
  49378. * Represents the range of an animation
  49379. */
  49380. var AnimationRange = /** @class */ (function () {
  49381. /**
  49382. * Initializes the range of an animation
  49383. * @param name The name of the animation range
  49384. * @param from The starting frame of the animation
  49385. * @param to The ending frame of the animation
  49386. */
  49387. function AnimationRange(
  49388. /**The name of the animation range**/
  49389. name,
  49390. /**The starting frame of the animation */
  49391. from,
  49392. /**The ending frame of the animation*/
  49393. to) {
  49394. this.name = name;
  49395. this.from = from;
  49396. this.to = to;
  49397. }
  49398. /**
  49399. * Makes a copy of the animation range
  49400. * @returns A copy of the animation range
  49401. */
  49402. AnimationRange.prototype.clone = function () {
  49403. return new AnimationRange(this.name, this.from, this.to);
  49404. };
  49405. return AnimationRange;
  49406. }());
  49407. BABYLON.AnimationRange = AnimationRange;
  49408. /**
  49409. * Composed of a frame, and an action function
  49410. */
  49411. var AnimationEvent = /** @class */ (function () {
  49412. /**
  49413. * Initializes the animation event
  49414. * @param frame The frame for which the event is triggered
  49415. * @param action The event to perform when triggered
  49416. * @param onlyOnce Specifies if the event should be triggered only once
  49417. */
  49418. function AnimationEvent(
  49419. /** The frame for which the event is triggered **/
  49420. frame,
  49421. /** The event to perform when triggered **/
  49422. action,
  49423. /** Specifies if the event should be triggered only once**/
  49424. onlyOnce) {
  49425. this.frame = frame;
  49426. this.action = action;
  49427. this.onlyOnce = onlyOnce;
  49428. /**
  49429. * Specifies if the animation event is done
  49430. */
  49431. this.isDone = false;
  49432. }
  49433. /** @hidden */
  49434. AnimationEvent.prototype._clone = function () {
  49435. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49436. };
  49437. return AnimationEvent;
  49438. }());
  49439. BABYLON.AnimationEvent = AnimationEvent;
  49440. /**
  49441. * A cursor which tracks a point on a path
  49442. */
  49443. var PathCursor = /** @class */ (function () {
  49444. /**
  49445. * Initializes the path cursor
  49446. * @param path The path to track
  49447. */
  49448. function PathCursor(path) {
  49449. this.path = path;
  49450. /**
  49451. * Stores path cursor callbacks for when an onchange event is triggered
  49452. */
  49453. this._onchange = new Array();
  49454. /**
  49455. * The value of the path cursor
  49456. */
  49457. this.value = 0;
  49458. /**
  49459. * The animation array of the path cursor
  49460. */
  49461. this.animations = new Array();
  49462. }
  49463. /**
  49464. * Gets the cursor point on the path
  49465. * @returns A point on the path cursor at the cursor location
  49466. */
  49467. PathCursor.prototype.getPoint = function () {
  49468. var point = this.path.getPointAtLengthPosition(this.value);
  49469. return new BABYLON.Vector3(point.x, 0, point.y);
  49470. };
  49471. /**
  49472. * Moves the cursor ahead by the step amount
  49473. * @param step The amount to move the cursor forward
  49474. * @returns This path cursor
  49475. */
  49476. PathCursor.prototype.moveAhead = function (step) {
  49477. if (step === void 0) { step = 0.002; }
  49478. this.move(step);
  49479. return this;
  49480. };
  49481. /**
  49482. * Moves the cursor behind by the step amount
  49483. * @param step The amount to move the cursor back
  49484. * @returns This path cursor
  49485. */
  49486. PathCursor.prototype.moveBack = function (step) {
  49487. if (step === void 0) { step = 0.002; }
  49488. this.move(-step);
  49489. return this;
  49490. };
  49491. /**
  49492. * Moves the cursor by the step amount
  49493. * If the step amount is greater than one, an exception is thrown
  49494. * @param step The amount to move the cursor
  49495. * @returns This path cursor
  49496. */
  49497. PathCursor.prototype.move = function (step) {
  49498. if (Math.abs(step) > 1) {
  49499. throw "step size should be less than 1.";
  49500. }
  49501. this.value += step;
  49502. this.ensureLimits();
  49503. this.raiseOnChange();
  49504. return this;
  49505. };
  49506. /**
  49507. * Ensures that the value is limited between zero and one
  49508. * @returns This path cursor
  49509. */
  49510. PathCursor.prototype.ensureLimits = function () {
  49511. while (this.value > 1) {
  49512. this.value -= 1;
  49513. }
  49514. while (this.value < 0) {
  49515. this.value += 1;
  49516. }
  49517. return this;
  49518. };
  49519. /**
  49520. * Runs onchange callbacks on change (used by the animation engine)
  49521. * @returns This path cursor
  49522. */
  49523. PathCursor.prototype.raiseOnChange = function () {
  49524. var _this = this;
  49525. this._onchange.forEach(function (f) { return f(_this); });
  49526. return this;
  49527. };
  49528. /**
  49529. * Executes a function on change
  49530. * @param f A path cursor onchange callback
  49531. * @returns This path cursor
  49532. */
  49533. PathCursor.prototype.onchange = function (f) {
  49534. this._onchange.push(f);
  49535. return this;
  49536. };
  49537. return PathCursor;
  49538. }());
  49539. BABYLON.PathCursor = PathCursor;
  49540. /**
  49541. * Enum for the animation key frame interpolation type
  49542. */
  49543. var AnimationKeyInterpolation;
  49544. (function (AnimationKeyInterpolation) {
  49545. /**
  49546. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49547. */
  49548. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49549. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49550. /**
  49551. * Class used to store any kind of animation
  49552. */
  49553. var Animation = /** @class */ (function () {
  49554. /**
  49555. * Initializes the animation
  49556. * @param name Name of the animation
  49557. * @param targetProperty Property to animate
  49558. * @param framePerSecond The frames per second of the animation
  49559. * @param dataType The data type of the animation
  49560. * @param loopMode The loop mode of the animation
  49561. * @param enableBlendings Specifies if blending should be enabled
  49562. */
  49563. function Animation(
  49564. /**Name of the animation */
  49565. name,
  49566. /**Property to animate */
  49567. targetProperty,
  49568. /**The frames per second of the animation */
  49569. framePerSecond,
  49570. /**The data type of the animation */
  49571. dataType,
  49572. /**The loop mode of the animation */
  49573. loopMode,
  49574. /**Specifies if blending should be enabled */
  49575. enableBlending) {
  49576. this.name = name;
  49577. this.targetProperty = targetProperty;
  49578. this.framePerSecond = framePerSecond;
  49579. this.dataType = dataType;
  49580. this.loopMode = loopMode;
  49581. this.enableBlending = enableBlending;
  49582. /**
  49583. * @hidden Internal use only
  49584. */
  49585. this._runtimeAnimations = new Array();
  49586. /**
  49587. * The set of event that will be linked to this animation
  49588. */
  49589. this._events = new Array();
  49590. /**
  49591. * Stores the blending speed of the animation
  49592. */
  49593. this.blendingSpeed = 0.01;
  49594. /**
  49595. * Stores the animation ranges for the animation
  49596. */
  49597. this._ranges = {};
  49598. this.targetPropertyPath = targetProperty.split(".");
  49599. this.dataType = dataType;
  49600. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49601. }
  49602. /**
  49603. * @hidden Internal use
  49604. */
  49605. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49606. var dataType = undefined;
  49607. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49608. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49609. }
  49610. else if (from instanceof BABYLON.Quaternion) {
  49611. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49612. }
  49613. else if (from instanceof BABYLON.Vector3) {
  49614. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49615. }
  49616. else if (from instanceof BABYLON.Vector2) {
  49617. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49618. }
  49619. else if (from instanceof BABYLON.Color3) {
  49620. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49621. }
  49622. else if (from instanceof BABYLON.Size) {
  49623. dataType = Animation.ANIMATIONTYPE_SIZE;
  49624. }
  49625. if (dataType == undefined) {
  49626. return null;
  49627. }
  49628. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49629. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49630. animation.setKeys(keys);
  49631. if (easingFunction !== undefined) {
  49632. animation.setEasingFunction(easingFunction);
  49633. }
  49634. return animation;
  49635. };
  49636. /**
  49637. * Sets up an animation
  49638. * @param property The property to animate
  49639. * @param animationType The animation type to apply
  49640. * @param framePerSecond The frames per second of the animation
  49641. * @param easingFunction The easing function used in the animation
  49642. * @returns The created animation
  49643. */
  49644. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49645. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49646. animation.setEasingFunction(easingFunction);
  49647. return animation;
  49648. };
  49649. /**
  49650. * Create and start an animation on a node
  49651. * @param name defines the name of the global animation that will be run on all nodes
  49652. * @param node defines the root node where the animation will take place
  49653. * @param targetProperty defines property to animate
  49654. * @param framePerSecond defines the number of frame per second yo use
  49655. * @param totalFrame defines the number of frames in total
  49656. * @param from defines the initial value
  49657. * @param to defines the final value
  49658. * @param loopMode defines which loop mode you want to use (off by default)
  49659. * @param easingFunction defines the easing function to use (linear by default)
  49660. * @param onAnimationEnd defines the callback to call when animation end
  49661. * @returns the animatable created for this animation
  49662. */
  49663. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49664. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49665. if (!animation) {
  49666. return null;
  49667. }
  49668. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49669. };
  49670. /**
  49671. * Create and start an animation on a node and its descendants
  49672. * @param name defines the name of the global animation that will be run on all nodes
  49673. * @param node defines the root node where the animation will take place
  49674. * @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
  49675. * @param targetProperty defines property to animate
  49676. * @param framePerSecond defines the number of frame per second to use
  49677. * @param totalFrame defines the number of frames in total
  49678. * @param from defines the initial value
  49679. * @param to defines the final value
  49680. * @param loopMode defines which loop mode you want to use (off by default)
  49681. * @param easingFunction defines the easing function to use (linear by default)
  49682. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49683. * @returns the list of animatables created for all nodes
  49684. * @example https://www.babylonjs-playground.com/#MH0VLI
  49685. */
  49686. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49687. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49688. if (!animation) {
  49689. return null;
  49690. }
  49691. var scene = node.getScene();
  49692. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49693. };
  49694. /**
  49695. * Creates a new animation, merges it with the existing animations and starts it
  49696. * @param name Name of the animation
  49697. * @param node Node which contains the scene that begins the animations
  49698. * @param targetProperty Specifies which property to animate
  49699. * @param framePerSecond The frames per second of the animation
  49700. * @param totalFrame The total number of frames
  49701. * @param from The frame at the beginning of the animation
  49702. * @param to The frame at the end of the animation
  49703. * @param loopMode Specifies the loop mode of the animation
  49704. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49705. * @param onAnimationEnd Callback to run once the animation is complete
  49706. * @returns Nullable animation
  49707. */
  49708. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49709. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49710. if (!animation) {
  49711. return null;
  49712. }
  49713. node.animations.push(animation);
  49714. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49715. };
  49716. /**
  49717. * Transition property of an host to the target Value
  49718. * @param property The property to transition
  49719. * @param targetValue The target Value of the property
  49720. * @param host The object where the property to animate belongs
  49721. * @param scene Scene used to run the animation
  49722. * @param frameRate Framerate (in frame/s) to use
  49723. * @param transition The transition type we want to use
  49724. * @param duration The duration of the animation, in milliseconds
  49725. * @param onAnimationEnd Callback trigger at the end of the animation
  49726. * @returns Nullable animation
  49727. */
  49728. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49729. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49730. if (duration <= 0) {
  49731. host[property] = targetValue;
  49732. if (onAnimationEnd) {
  49733. onAnimationEnd();
  49734. }
  49735. return null;
  49736. }
  49737. var endFrame = frameRate * (duration / 1000);
  49738. transition.setKeys([{
  49739. frame: 0,
  49740. value: host[property].clone ? host[property].clone() : host[property]
  49741. },
  49742. {
  49743. frame: endFrame,
  49744. value: targetValue
  49745. }]);
  49746. if (!host.animations) {
  49747. host.animations = [];
  49748. }
  49749. host.animations.push(transition);
  49750. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49751. animation.onAnimationEnd = onAnimationEnd;
  49752. return animation;
  49753. };
  49754. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49755. /**
  49756. * Return the array of runtime animations currently using this animation
  49757. */
  49758. get: function () {
  49759. return this._runtimeAnimations;
  49760. },
  49761. enumerable: true,
  49762. configurable: true
  49763. });
  49764. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49765. /**
  49766. * Specifies if any of the runtime animations are currently running
  49767. */
  49768. get: function () {
  49769. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49770. var runtimeAnimation = _a[_i];
  49771. if (!runtimeAnimation.isStopped) {
  49772. return true;
  49773. }
  49774. }
  49775. return false;
  49776. },
  49777. enumerable: true,
  49778. configurable: true
  49779. });
  49780. // Methods
  49781. /**
  49782. * Converts the animation to a string
  49783. * @param fullDetails support for multiple levels of logging within scene loading
  49784. * @returns String form of the animation
  49785. */
  49786. Animation.prototype.toString = function (fullDetails) {
  49787. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49788. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49789. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49790. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49791. if (fullDetails) {
  49792. ret += ", Ranges: {";
  49793. var first = true;
  49794. for (var name in this._ranges) {
  49795. if (first) {
  49796. ret += ", ";
  49797. first = false;
  49798. }
  49799. ret += name;
  49800. }
  49801. ret += "}";
  49802. }
  49803. return ret;
  49804. };
  49805. /**
  49806. * Add an event to this animation
  49807. * @param event Event to add
  49808. */
  49809. Animation.prototype.addEvent = function (event) {
  49810. this._events.push(event);
  49811. };
  49812. /**
  49813. * Remove all events found at the given frame
  49814. * @param frame The frame to remove events from
  49815. */
  49816. Animation.prototype.removeEvents = function (frame) {
  49817. for (var index = 0; index < this._events.length; index++) {
  49818. if (this._events[index].frame === frame) {
  49819. this._events.splice(index, 1);
  49820. index--;
  49821. }
  49822. }
  49823. };
  49824. /**
  49825. * Retrieves all the events from the animation
  49826. * @returns Events from the animation
  49827. */
  49828. Animation.prototype.getEvents = function () {
  49829. return this._events;
  49830. };
  49831. /**
  49832. * Creates an animation range
  49833. * @param name Name of the animation range
  49834. * @param from Starting frame of the animation range
  49835. * @param to Ending frame of the animation
  49836. */
  49837. Animation.prototype.createRange = function (name, from, to) {
  49838. // check name not already in use; could happen for bones after serialized
  49839. if (!this._ranges[name]) {
  49840. this._ranges[name] = new AnimationRange(name, from, to);
  49841. }
  49842. };
  49843. /**
  49844. * Deletes an animation range by name
  49845. * @param name Name of the animation range to delete
  49846. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49847. */
  49848. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49849. if (deleteFrames === void 0) { deleteFrames = true; }
  49850. var range = this._ranges[name];
  49851. if (!range) {
  49852. return;
  49853. }
  49854. if (deleteFrames) {
  49855. var from = range.from;
  49856. var to = range.to;
  49857. // this loop MUST go high to low for multiple splices to work
  49858. for (var key = this._keys.length - 1; key >= 0; key--) {
  49859. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49860. this._keys.splice(key, 1);
  49861. }
  49862. }
  49863. }
  49864. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49865. };
  49866. /**
  49867. * Gets the animation range by name, or null if not defined
  49868. * @param name Name of the animation range
  49869. * @returns Nullable animation range
  49870. */
  49871. Animation.prototype.getRange = function (name) {
  49872. return this._ranges[name];
  49873. };
  49874. /**
  49875. * Gets the key frames from the animation
  49876. * @returns The key frames of the animation
  49877. */
  49878. Animation.prototype.getKeys = function () {
  49879. return this._keys;
  49880. };
  49881. /**
  49882. * Gets the highest frame rate of the animation
  49883. * @returns Highest frame rate of the animation
  49884. */
  49885. Animation.prototype.getHighestFrame = function () {
  49886. var ret = 0;
  49887. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49888. if (ret < this._keys[key].frame) {
  49889. ret = this._keys[key].frame;
  49890. }
  49891. }
  49892. return ret;
  49893. };
  49894. /**
  49895. * Gets the easing function of the animation
  49896. * @returns Easing function of the animation
  49897. */
  49898. Animation.prototype.getEasingFunction = function () {
  49899. return this._easingFunction;
  49900. };
  49901. /**
  49902. * Sets the easing function of the animation
  49903. * @param easingFunction A custom mathematical formula for animation
  49904. */
  49905. Animation.prototype.setEasingFunction = function (easingFunction) {
  49906. this._easingFunction = easingFunction;
  49907. };
  49908. /**
  49909. * Interpolates a scalar linearly
  49910. * @param startValue Start value of the animation curve
  49911. * @param endValue End value of the animation curve
  49912. * @param gradient Scalar amount to interpolate
  49913. * @returns Interpolated scalar value
  49914. */
  49915. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49916. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49917. };
  49918. /**
  49919. * Interpolates a scalar cubically
  49920. * @param startValue Start value of the animation curve
  49921. * @param outTangent End tangent of the animation
  49922. * @param endValue End value of the animation curve
  49923. * @param inTangent Start tangent of the animation curve
  49924. * @param gradient Scalar amount to interpolate
  49925. * @returns Interpolated scalar value
  49926. */
  49927. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49928. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49929. };
  49930. /**
  49931. * Interpolates a quaternion using a spherical linear interpolation
  49932. * @param startValue Start value of the animation curve
  49933. * @param endValue End value of the animation curve
  49934. * @param gradient Scalar amount to interpolate
  49935. * @returns Interpolated quaternion value
  49936. */
  49937. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49938. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49939. };
  49940. /**
  49941. * Interpolates a quaternion cubically
  49942. * @param startValue Start value of the animation curve
  49943. * @param outTangent End tangent of the animation curve
  49944. * @param endValue End value of the animation curve
  49945. * @param inTangent Start tangent of the animation curve
  49946. * @param gradient Scalar amount to interpolate
  49947. * @returns Interpolated quaternion value
  49948. */
  49949. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49950. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49951. };
  49952. /**
  49953. * Interpolates a Vector3 linearl
  49954. * @param startValue Start value of the animation curve
  49955. * @param endValue End value of the animation curve
  49956. * @param gradient Scalar amount to interpolate
  49957. * @returns Interpolated scalar value
  49958. */
  49959. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49960. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49961. };
  49962. /**
  49963. * Interpolates a Vector3 cubically
  49964. * @param startValue Start value of the animation curve
  49965. * @param outTangent End tangent of the animation
  49966. * @param endValue End value of the animation curve
  49967. * @param inTangent Start tangent of the animation curve
  49968. * @param gradient Scalar amount to interpolate
  49969. * @returns InterpolatedVector3 value
  49970. */
  49971. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49972. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49973. };
  49974. /**
  49975. * Interpolates a Vector2 linearly
  49976. * @param startValue Start value of the animation curve
  49977. * @param endValue End value of the animation curve
  49978. * @param gradient Scalar amount to interpolate
  49979. * @returns Interpolated Vector2 value
  49980. */
  49981. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49982. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49983. };
  49984. /**
  49985. * Interpolates a Vector2 cubically
  49986. * @param startValue Start value of the animation curve
  49987. * @param outTangent End tangent of the animation
  49988. * @param endValue End value of the animation curve
  49989. * @param inTangent Start tangent of the animation curve
  49990. * @param gradient Scalar amount to interpolate
  49991. * @returns Interpolated Vector2 value
  49992. */
  49993. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49994. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49995. };
  49996. /**
  49997. * Interpolates a size linearly
  49998. * @param startValue Start value of the animation curve
  49999. * @param endValue End value of the animation curve
  50000. * @param gradient Scalar amount to interpolate
  50001. * @returns Interpolated Size value
  50002. */
  50003. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50004. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50005. };
  50006. /**
  50007. * Interpolates a Color3 linearly
  50008. * @param startValue Start value of the animation curve
  50009. * @param endValue End value of the animation curve
  50010. * @param gradient Scalar amount to interpolate
  50011. * @returns Interpolated Color3 value
  50012. */
  50013. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50014. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50015. };
  50016. /**
  50017. * @hidden Internal use only
  50018. */
  50019. Animation.prototype._getKeyValue = function (value) {
  50020. if (typeof value === "function") {
  50021. return value();
  50022. }
  50023. return value;
  50024. };
  50025. /**
  50026. * @hidden Internal use only
  50027. */
  50028. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50029. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50030. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50031. }
  50032. var keys = this.getKeys();
  50033. // Try to get a hash to find the right key
  50034. 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));
  50035. if (keys[startKeyIndex].frame >= currentFrame) {
  50036. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50037. startKeyIndex--;
  50038. }
  50039. }
  50040. for (var key = startKeyIndex; key < keys.length; key++) {
  50041. var endKey = keys[key + 1];
  50042. if (endKey.frame >= currentFrame) {
  50043. var startKey = keys[key];
  50044. var startValue = this._getKeyValue(startKey.value);
  50045. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50046. return startValue;
  50047. }
  50048. var endValue = this._getKeyValue(endKey.value);
  50049. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50050. var frameDelta = endKey.frame - startKey.frame;
  50051. // gradient : percent of currentFrame between the frame inf and the frame sup
  50052. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50053. // check for easingFunction and correction of gradient
  50054. var easingFunction = this.getEasingFunction();
  50055. if (easingFunction != null) {
  50056. gradient = easingFunction.ease(gradient);
  50057. }
  50058. switch (this.dataType) {
  50059. // Float
  50060. case Animation.ANIMATIONTYPE_FLOAT:
  50061. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50062. switch (loopMode) {
  50063. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50064. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50065. return floatValue;
  50066. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50067. return offsetValue * repeatCount + floatValue;
  50068. }
  50069. break;
  50070. // Quaternion
  50071. case Animation.ANIMATIONTYPE_QUATERNION:
  50072. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50073. switch (loopMode) {
  50074. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50075. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50076. return quatValue;
  50077. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50078. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50079. }
  50080. return quatValue;
  50081. // Vector3
  50082. case Animation.ANIMATIONTYPE_VECTOR3:
  50083. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50084. switch (loopMode) {
  50085. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50086. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50087. return vec3Value;
  50088. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50089. return vec3Value.add(offsetValue.scale(repeatCount));
  50090. }
  50091. // Vector2
  50092. case Animation.ANIMATIONTYPE_VECTOR2:
  50093. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50094. switch (loopMode) {
  50095. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50096. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50097. return vec2Value;
  50098. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50099. return vec2Value.add(offsetValue.scale(repeatCount));
  50100. }
  50101. // Size
  50102. case Animation.ANIMATIONTYPE_SIZE:
  50103. switch (loopMode) {
  50104. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50105. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50106. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50107. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50108. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50109. }
  50110. // Color3
  50111. case Animation.ANIMATIONTYPE_COLOR3:
  50112. switch (loopMode) {
  50113. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50114. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50115. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50116. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50117. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50118. }
  50119. // Matrix
  50120. case Animation.ANIMATIONTYPE_MATRIX:
  50121. switch (loopMode) {
  50122. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50123. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50124. if (Animation.AllowMatricesInterpolation) {
  50125. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50126. }
  50127. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50128. return startValue;
  50129. }
  50130. default:
  50131. break;
  50132. }
  50133. break;
  50134. }
  50135. }
  50136. return this._getKeyValue(keys[keys.length - 1].value);
  50137. };
  50138. /**
  50139. * Defines the function to use to interpolate matrices
  50140. * @param startValue defines the start matrix
  50141. * @param endValue defines the end matrix
  50142. * @param gradient defines the gradient between both matrices
  50143. * @param result defines an optional target matrix where to store the interpolation
  50144. * @returns the interpolated matrix
  50145. */
  50146. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50147. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50148. if (result) {
  50149. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50150. return result;
  50151. }
  50152. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50153. }
  50154. if (result) {
  50155. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50156. return result;
  50157. }
  50158. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50159. };
  50160. /**
  50161. * Makes a copy of the animation
  50162. * @returns Cloned animation
  50163. */
  50164. Animation.prototype.clone = function () {
  50165. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50166. clone.enableBlending = this.enableBlending;
  50167. clone.blendingSpeed = this.blendingSpeed;
  50168. if (this._keys) {
  50169. clone.setKeys(this._keys);
  50170. }
  50171. if (this._ranges) {
  50172. clone._ranges = {};
  50173. for (var name in this._ranges) {
  50174. var range = this._ranges[name];
  50175. if (!range) {
  50176. continue;
  50177. }
  50178. clone._ranges[name] = range.clone();
  50179. }
  50180. }
  50181. return clone;
  50182. };
  50183. /**
  50184. * Sets the key frames of the animation
  50185. * @param values The animation key frames to set
  50186. */
  50187. Animation.prototype.setKeys = function (values) {
  50188. this._keys = values.slice(0);
  50189. };
  50190. /**
  50191. * Serializes the animation to an object
  50192. * @returns Serialized object
  50193. */
  50194. Animation.prototype.serialize = function () {
  50195. var serializationObject = {};
  50196. serializationObject.name = this.name;
  50197. serializationObject.property = this.targetProperty;
  50198. serializationObject.framePerSecond = this.framePerSecond;
  50199. serializationObject.dataType = this.dataType;
  50200. serializationObject.loopBehavior = this.loopMode;
  50201. serializationObject.enableBlending = this.enableBlending;
  50202. serializationObject.blendingSpeed = this.blendingSpeed;
  50203. var dataType = this.dataType;
  50204. serializationObject.keys = [];
  50205. var keys = this.getKeys();
  50206. for (var index = 0; index < keys.length; index++) {
  50207. var animationKey = keys[index];
  50208. var key = {};
  50209. key.frame = animationKey.frame;
  50210. switch (dataType) {
  50211. case Animation.ANIMATIONTYPE_FLOAT:
  50212. key.values = [animationKey.value];
  50213. break;
  50214. case Animation.ANIMATIONTYPE_QUATERNION:
  50215. case Animation.ANIMATIONTYPE_MATRIX:
  50216. case Animation.ANIMATIONTYPE_VECTOR3:
  50217. case Animation.ANIMATIONTYPE_COLOR3:
  50218. key.values = animationKey.value.asArray();
  50219. break;
  50220. }
  50221. serializationObject.keys.push(key);
  50222. }
  50223. serializationObject.ranges = [];
  50224. for (var name in this._ranges) {
  50225. var source = this._ranges[name];
  50226. if (!source) {
  50227. continue;
  50228. }
  50229. var range = {};
  50230. range.name = name;
  50231. range.from = source.from;
  50232. range.to = source.to;
  50233. serializationObject.ranges.push(range);
  50234. }
  50235. return serializationObject;
  50236. };
  50237. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50238. /**
  50239. * Get the float animation type
  50240. */
  50241. get: function () {
  50242. return Animation._ANIMATIONTYPE_FLOAT;
  50243. },
  50244. enumerable: true,
  50245. configurable: true
  50246. });
  50247. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50248. /**
  50249. * Get the Vector3 animation type
  50250. */
  50251. get: function () {
  50252. return Animation._ANIMATIONTYPE_VECTOR3;
  50253. },
  50254. enumerable: true,
  50255. configurable: true
  50256. });
  50257. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50258. /**
  50259. * Get the Vector2 animation type
  50260. */
  50261. get: function () {
  50262. return Animation._ANIMATIONTYPE_VECTOR2;
  50263. },
  50264. enumerable: true,
  50265. configurable: true
  50266. });
  50267. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50268. /**
  50269. * Get the Size animation type
  50270. */
  50271. get: function () {
  50272. return Animation._ANIMATIONTYPE_SIZE;
  50273. },
  50274. enumerable: true,
  50275. configurable: true
  50276. });
  50277. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50278. /**
  50279. * Get the Quaternion animation type
  50280. */
  50281. get: function () {
  50282. return Animation._ANIMATIONTYPE_QUATERNION;
  50283. },
  50284. enumerable: true,
  50285. configurable: true
  50286. });
  50287. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50288. /**
  50289. * Get the Matrix animation type
  50290. */
  50291. get: function () {
  50292. return Animation._ANIMATIONTYPE_MATRIX;
  50293. },
  50294. enumerable: true,
  50295. configurable: true
  50296. });
  50297. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50298. /**
  50299. * Get the Color3 animation type
  50300. */
  50301. get: function () {
  50302. return Animation._ANIMATIONTYPE_COLOR3;
  50303. },
  50304. enumerable: true,
  50305. configurable: true
  50306. });
  50307. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50308. /**
  50309. * Get the Relative Loop Mode
  50310. */
  50311. get: function () {
  50312. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50313. },
  50314. enumerable: true,
  50315. configurable: true
  50316. });
  50317. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50318. /**
  50319. * Get the Cycle Loop Mode
  50320. */
  50321. get: function () {
  50322. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50323. },
  50324. enumerable: true,
  50325. configurable: true
  50326. });
  50327. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50328. /**
  50329. * Get the Constant Loop Mode
  50330. */
  50331. get: function () {
  50332. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50333. },
  50334. enumerable: true,
  50335. configurable: true
  50336. });
  50337. /** @hidden */
  50338. Animation._UniversalLerp = function (left, right, amount) {
  50339. var constructor = left.constructor;
  50340. if (constructor.Lerp) { // Lerp supported
  50341. return constructor.Lerp(left, right, amount);
  50342. }
  50343. else if (constructor.Slerp) { // Slerp supported
  50344. return constructor.Slerp(left, right, amount);
  50345. }
  50346. else if (left.toFixed) { // Number
  50347. return left * (1.0 - amount) + amount * right;
  50348. }
  50349. else { // Blending not supported
  50350. return right;
  50351. }
  50352. };
  50353. /**
  50354. * Parses an animation object and creates an animation
  50355. * @param parsedAnimation Parsed animation object
  50356. * @returns Animation object
  50357. */
  50358. Animation.Parse = function (parsedAnimation) {
  50359. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50360. var dataType = parsedAnimation.dataType;
  50361. var keys = [];
  50362. var data;
  50363. var index;
  50364. if (parsedAnimation.enableBlending) {
  50365. animation.enableBlending = parsedAnimation.enableBlending;
  50366. }
  50367. if (parsedAnimation.blendingSpeed) {
  50368. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50369. }
  50370. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50371. var key = parsedAnimation.keys[index];
  50372. var inTangent;
  50373. var outTangent;
  50374. switch (dataType) {
  50375. case Animation.ANIMATIONTYPE_FLOAT:
  50376. data = key.values[0];
  50377. if (key.values.length >= 1) {
  50378. inTangent = key.values[1];
  50379. }
  50380. if (key.values.length >= 2) {
  50381. outTangent = key.values[2];
  50382. }
  50383. break;
  50384. case Animation.ANIMATIONTYPE_QUATERNION:
  50385. data = BABYLON.Quaternion.FromArray(key.values);
  50386. if (key.values.length >= 8) {
  50387. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50388. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50389. inTangent = _inTangent;
  50390. }
  50391. }
  50392. if (key.values.length >= 12) {
  50393. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50394. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50395. outTangent = _outTangent;
  50396. }
  50397. }
  50398. break;
  50399. case Animation.ANIMATIONTYPE_MATRIX:
  50400. data = BABYLON.Matrix.FromArray(key.values);
  50401. break;
  50402. case Animation.ANIMATIONTYPE_COLOR3:
  50403. data = BABYLON.Color3.FromArray(key.values);
  50404. break;
  50405. case Animation.ANIMATIONTYPE_VECTOR3:
  50406. default:
  50407. data = BABYLON.Vector3.FromArray(key.values);
  50408. break;
  50409. }
  50410. var keyData = {};
  50411. keyData.frame = key.frame;
  50412. keyData.value = data;
  50413. if (inTangent != undefined) {
  50414. keyData.inTangent = inTangent;
  50415. }
  50416. if (outTangent != undefined) {
  50417. keyData.outTangent = outTangent;
  50418. }
  50419. keys.push(keyData);
  50420. }
  50421. animation.setKeys(keys);
  50422. if (parsedAnimation.ranges) {
  50423. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50424. data = parsedAnimation.ranges[index];
  50425. animation.createRange(data.name, data.from, data.to);
  50426. }
  50427. }
  50428. return animation;
  50429. };
  50430. /**
  50431. * Appends the serialized animations from the source animations
  50432. * @param source Source containing the animations
  50433. * @param destination Target to store the animations
  50434. */
  50435. Animation.AppendSerializedAnimations = function (source, destination) {
  50436. if (source.animations) {
  50437. destination.animations = [];
  50438. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50439. var animation = source.animations[animationIndex];
  50440. destination.animations.push(animation.serialize());
  50441. }
  50442. }
  50443. };
  50444. /**
  50445. * Use matrix interpolation instead of using direct key value when animating matrices
  50446. */
  50447. Animation.AllowMatricesInterpolation = false;
  50448. /**
  50449. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50450. */
  50451. Animation.AllowMatrixDecomposeForInterpolation = true;
  50452. // Statics
  50453. /**
  50454. * Float animation type
  50455. */
  50456. Animation._ANIMATIONTYPE_FLOAT = 0;
  50457. /**
  50458. * Vector3 animation type
  50459. */
  50460. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50461. /**
  50462. * Quaternion animation type
  50463. */
  50464. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50465. /**
  50466. * Matrix animation type
  50467. */
  50468. Animation._ANIMATIONTYPE_MATRIX = 3;
  50469. /**
  50470. * Color3 animation type
  50471. */
  50472. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50473. /**
  50474. * Vector2 animation type
  50475. */
  50476. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50477. /**
  50478. * Size animation type
  50479. */
  50480. Animation._ANIMATIONTYPE_SIZE = 6;
  50481. /**
  50482. * Relative Loop Mode
  50483. */
  50484. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50485. /**
  50486. * Cycle Loop Mode
  50487. */
  50488. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50489. /**
  50490. * Constant Loop Mode
  50491. */
  50492. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50493. return Animation;
  50494. }());
  50495. BABYLON.Animation = Animation;
  50496. })(BABYLON || (BABYLON = {}));
  50497. //# sourceMappingURL=babylon.animation.js.map
  50498. var BABYLON;
  50499. (function (BABYLON) {
  50500. /**
  50501. * This class defines the direct association between an animation and a target
  50502. */
  50503. var TargetedAnimation = /** @class */ (function () {
  50504. function TargetedAnimation() {
  50505. }
  50506. return TargetedAnimation;
  50507. }());
  50508. BABYLON.TargetedAnimation = TargetedAnimation;
  50509. /**
  50510. * Use this class to create coordinated animations on multiple targets
  50511. */
  50512. var AnimationGroup = /** @class */ (function () {
  50513. function AnimationGroup(name, scene) {
  50514. if (scene === void 0) { scene = null; }
  50515. this.name = name;
  50516. this._targetedAnimations = new Array();
  50517. this._animatables = new Array();
  50518. this._from = Number.MAX_VALUE;
  50519. this._to = -Number.MAX_VALUE;
  50520. this._speedRatio = 1;
  50521. this.onAnimationEndObservable = new BABYLON.Observable();
  50522. /**
  50523. * This observable will notify when all animations have ended.
  50524. */
  50525. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50526. /**
  50527. * This observable will notify when all animations have paused.
  50528. */
  50529. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50530. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50531. this._scene.animationGroups.push(this);
  50532. }
  50533. Object.defineProperty(AnimationGroup.prototype, "from", {
  50534. /**
  50535. * Gets the first frame
  50536. */
  50537. get: function () {
  50538. return this._from;
  50539. },
  50540. enumerable: true,
  50541. configurable: true
  50542. });
  50543. Object.defineProperty(AnimationGroup.prototype, "to", {
  50544. /**
  50545. * Gets the last frame
  50546. */
  50547. get: function () {
  50548. return this._to;
  50549. },
  50550. enumerable: true,
  50551. configurable: true
  50552. });
  50553. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50554. /**
  50555. * Define if the animations are started
  50556. */
  50557. get: function () {
  50558. return this._isStarted;
  50559. },
  50560. enumerable: true,
  50561. configurable: true
  50562. });
  50563. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50564. /**
  50565. * Gets or sets the speed ratio to use for all animations
  50566. */
  50567. get: function () {
  50568. return this._speedRatio;
  50569. },
  50570. /**
  50571. * Gets or sets the speed ratio to use for all animations
  50572. */
  50573. set: function (value) {
  50574. if (this._speedRatio === value) {
  50575. return;
  50576. }
  50577. this._speedRatio = value;
  50578. for (var index = 0; index < this._animatables.length; index++) {
  50579. var animatable = this._animatables[index];
  50580. animatable.speedRatio = this._speedRatio;
  50581. }
  50582. },
  50583. enumerable: true,
  50584. configurable: true
  50585. });
  50586. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50587. /**
  50588. * Gets the targeted animations for this animation group
  50589. */
  50590. get: function () {
  50591. return this._targetedAnimations;
  50592. },
  50593. enumerable: true,
  50594. configurable: true
  50595. });
  50596. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50597. /**
  50598. * returning the list of animatables controlled by this animation group.
  50599. */
  50600. get: function () {
  50601. return this._animatables;
  50602. },
  50603. enumerable: true,
  50604. configurable: true
  50605. });
  50606. /**
  50607. * Add an animation (with its target) in the group
  50608. * @param animation defines the animation we want to add
  50609. * @param target defines the target of the animation
  50610. * @returns the {BABYLON.TargetedAnimation} object
  50611. */
  50612. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50613. var targetedAnimation = {
  50614. animation: animation,
  50615. target: target
  50616. };
  50617. var keys = animation.getKeys();
  50618. if (this._from > keys[0].frame) {
  50619. this._from = keys[0].frame;
  50620. }
  50621. if (this._to < keys[keys.length - 1].frame) {
  50622. this._to = keys[keys.length - 1].frame;
  50623. }
  50624. this._targetedAnimations.push(targetedAnimation);
  50625. return targetedAnimation;
  50626. };
  50627. /**
  50628. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50629. * It can add constant keys at begin or end
  50630. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50631. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50632. */
  50633. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50634. if (beginFrame === void 0) { beginFrame = null; }
  50635. if (endFrame === void 0) { endFrame = null; }
  50636. if (beginFrame == null)
  50637. beginFrame = this._from;
  50638. if (endFrame == null)
  50639. endFrame = this._to;
  50640. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50641. var targetedAnimation = this._targetedAnimations[index];
  50642. var keys = targetedAnimation.animation.getKeys();
  50643. var startKey = keys[0];
  50644. var endKey = keys[keys.length - 1];
  50645. if (startKey.frame > beginFrame) {
  50646. var newKey = {
  50647. frame: beginFrame,
  50648. value: startKey.value,
  50649. inTangent: startKey.inTangent,
  50650. outTangent: startKey.outTangent,
  50651. interpolation: startKey.interpolation
  50652. };
  50653. keys.splice(0, 0, newKey);
  50654. }
  50655. if (endKey.frame < endFrame) {
  50656. var newKey = {
  50657. frame: endFrame,
  50658. value: endKey.value,
  50659. inTangent: endKey.outTangent,
  50660. outTangent: endKey.outTangent,
  50661. interpolation: endKey.interpolation
  50662. };
  50663. keys.push(newKey);
  50664. }
  50665. }
  50666. this._from = beginFrame;
  50667. this._to = endFrame;
  50668. return this;
  50669. };
  50670. /**
  50671. * Start all animations on given targets
  50672. * @param loop defines if animations must loop
  50673. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50674. * @param from defines the from key (optional)
  50675. * @param to defines the to key (optional)
  50676. * @returns the current animation group
  50677. */
  50678. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50679. var _this = this;
  50680. if (loop === void 0) { loop = false; }
  50681. if (speedRatio === void 0) { speedRatio = 1; }
  50682. if (this._isStarted || this._targetedAnimations.length === 0) {
  50683. return this;
  50684. }
  50685. var _loop_1 = function (targetedAnimation) {
  50686. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50687. animatable.onAnimationEnd = function () {
  50688. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50689. _this._checkAnimationGroupEnded(animatable);
  50690. };
  50691. this_1._animatables.push(animatable);
  50692. };
  50693. var this_1 = this;
  50694. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50695. var targetedAnimation = _a[_i];
  50696. _loop_1(targetedAnimation);
  50697. }
  50698. this._speedRatio = speedRatio;
  50699. this._isStarted = true;
  50700. return this;
  50701. };
  50702. /**
  50703. * Pause all animations
  50704. */
  50705. AnimationGroup.prototype.pause = function () {
  50706. if (!this._isStarted) {
  50707. return this;
  50708. }
  50709. for (var index = 0; index < this._animatables.length; index++) {
  50710. var animatable = this._animatables[index];
  50711. animatable.pause();
  50712. }
  50713. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50714. return this;
  50715. };
  50716. /**
  50717. * Play all animations to initial state
  50718. * This function will start() the animations if they were not started or will restart() them if they were paused
  50719. * @param loop defines if animations must loop
  50720. */
  50721. AnimationGroup.prototype.play = function (loop) {
  50722. // only if all animatables are ready and exist
  50723. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50724. if (loop !== undefined) {
  50725. for (var index = 0; index < this._animatables.length; index++) {
  50726. var animatable = this._animatables[index];
  50727. animatable.loopAnimation = loop;
  50728. }
  50729. }
  50730. this.restart();
  50731. }
  50732. else {
  50733. this.stop();
  50734. this.start(loop, this._speedRatio);
  50735. }
  50736. return this;
  50737. };
  50738. /**
  50739. * Reset all animations to initial state
  50740. */
  50741. AnimationGroup.prototype.reset = function () {
  50742. if (!this._isStarted) {
  50743. return this;
  50744. }
  50745. for (var index = 0; index < this._animatables.length; index++) {
  50746. var animatable = this._animatables[index];
  50747. animatable.reset();
  50748. }
  50749. return this;
  50750. };
  50751. /**
  50752. * Restart animations from key 0
  50753. */
  50754. AnimationGroup.prototype.restart = function () {
  50755. if (!this._isStarted) {
  50756. return this;
  50757. }
  50758. for (var index = 0; index < this._animatables.length; index++) {
  50759. var animatable = this._animatables[index];
  50760. animatable.restart();
  50761. }
  50762. return this;
  50763. };
  50764. /**
  50765. * Stop all animations
  50766. */
  50767. AnimationGroup.prototype.stop = function () {
  50768. if (!this._isStarted) {
  50769. return this;
  50770. }
  50771. var list = this._animatables.slice();
  50772. for (var index = 0; index < list.length; index++) {
  50773. list[index].stop();
  50774. }
  50775. this._isStarted = false;
  50776. return this;
  50777. };
  50778. /**
  50779. * Set animation weight for all animatables
  50780. * @param weight defines the weight to use
  50781. * @return the animationGroup
  50782. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50783. */
  50784. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50785. for (var index = 0; index < this._animatables.length; index++) {
  50786. var animatable = this._animatables[index];
  50787. animatable.weight = weight;
  50788. }
  50789. return this;
  50790. };
  50791. /**
  50792. * Synchronize and normalize all animatables with a source animatable
  50793. * @param root defines the root animatable to synchronize with
  50794. * @return the animationGroup
  50795. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50796. */
  50797. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50798. for (var index = 0; index < this._animatables.length; index++) {
  50799. var animatable = this._animatables[index];
  50800. animatable.syncWith(root);
  50801. }
  50802. return this;
  50803. };
  50804. /**
  50805. * Goes to a specific frame in this animation group
  50806. * @param frame the frame number to go to
  50807. * @return the animationGroup
  50808. */
  50809. AnimationGroup.prototype.goToFrame = function (frame) {
  50810. if (!this._isStarted) {
  50811. return this;
  50812. }
  50813. for (var index = 0; index < this._animatables.length; index++) {
  50814. var animatable = this._animatables[index];
  50815. animatable.goToFrame(frame);
  50816. }
  50817. return this;
  50818. };
  50819. /**
  50820. * Dispose all associated resources
  50821. */
  50822. AnimationGroup.prototype.dispose = function () {
  50823. this._targetedAnimations = [];
  50824. this._animatables = [];
  50825. var index = this._scene.animationGroups.indexOf(this);
  50826. if (index > -1) {
  50827. this._scene.animationGroups.splice(index, 1);
  50828. }
  50829. };
  50830. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50831. // animatable should be taken out of the array
  50832. var idx = this._animatables.indexOf(animatable);
  50833. if (idx > -1) {
  50834. this._animatables.splice(idx, 1);
  50835. }
  50836. // all animatables were removed? animation group ended!
  50837. if (this._animatables.length === 0) {
  50838. this._isStarted = false;
  50839. this.onAnimationGroupEndObservable.notifyObservers(this);
  50840. }
  50841. };
  50842. return AnimationGroup;
  50843. }());
  50844. BABYLON.AnimationGroup = AnimationGroup;
  50845. })(BABYLON || (BABYLON = {}));
  50846. //# sourceMappingURL=babylon.animationGroup.js.map
  50847. var BABYLON;
  50848. (function (BABYLON) {
  50849. /**
  50850. * Defines a runtime animation
  50851. */
  50852. var RuntimeAnimation = /** @class */ (function () {
  50853. /**
  50854. * Create a new RuntimeAnimation object
  50855. * @param target defines the target of the animation
  50856. * @param animation defines the source animation object
  50857. * @param scene defines the hosting scene
  50858. * @param host defines the initiating Animatable
  50859. */
  50860. function RuntimeAnimation(target, animation, scene, host) {
  50861. var _this = this;
  50862. this._events = new Array();
  50863. /**
  50864. * The current frame of the runtime animation
  50865. */
  50866. this._currentFrame = 0;
  50867. /**
  50868. * The original value of the runtime animation
  50869. */
  50870. this._originalValue = new Array();
  50871. /**
  50872. * The offsets cache of the runtime animation
  50873. */
  50874. this._offsetsCache = {};
  50875. /**
  50876. * The high limits cache of the runtime animation
  50877. */
  50878. this._highLimitsCache = {};
  50879. /**
  50880. * Specifies if the runtime animation has been stopped
  50881. */
  50882. this._stopped = false;
  50883. /**
  50884. * The blending factor of the runtime animation
  50885. */
  50886. this._blendingFactor = 0;
  50887. /**
  50888. * The target path of the runtime animation
  50889. */
  50890. this._targetPath = "";
  50891. /**
  50892. * The weight of the runtime animation
  50893. */
  50894. this._weight = 1.0;
  50895. /**
  50896. * The ratio offset of the runtime animation
  50897. */
  50898. this._ratioOffset = 0;
  50899. /**
  50900. * The previous delay of the runtime animation
  50901. */
  50902. this._previousDelay = 0;
  50903. /**
  50904. * The previous ratio of the runtime animation
  50905. */
  50906. this._previousRatio = 0;
  50907. this._animation = animation;
  50908. this._target = target;
  50909. this._scene = scene;
  50910. this._host = host;
  50911. animation._runtimeAnimations.push(this);
  50912. // Cloning events locally
  50913. var events = animation.getEvents();
  50914. if (events && events.length > 0) {
  50915. events.forEach(function (e) {
  50916. _this._events.push(e._clone());
  50917. });
  50918. }
  50919. }
  50920. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50921. /**
  50922. * Gets the current frame of the runtime animation
  50923. */
  50924. get: function () {
  50925. return this._currentFrame;
  50926. },
  50927. enumerable: true,
  50928. configurable: true
  50929. });
  50930. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50931. /**
  50932. * Gets the weight of the runtime animation
  50933. */
  50934. get: function () {
  50935. return this._weight;
  50936. },
  50937. enumerable: true,
  50938. configurable: true
  50939. });
  50940. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50941. /**
  50942. * Gets the current value of the runtime animation
  50943. */
  50944. get: function () {
  50945. return this._currentValue;
  50946. },
  50947. enumerable: true,
  50948. configurable: true
  50949. });
  50950. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50951. /**
  50952. * Gets the target path of the runtime animation
  50953. */
  50954. get: function () {
  50955. return this._targetPath;
  50956. },
  50957. enumerable: true,
  50958. configurable: true
  50959. });
  50960. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50961. /**
  50962. * Gets the actual target of the runtime animation
  50963. */
  50964. get: function () {
  50965. return this._activeTarget;
  50966. },
  50967. enumerable: true,
  50968. configurable: true
  50969. });
  50970. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50971. /**
  50972. * Gets the animation from the runtime animation
  50973. */
  50974. get: function () {
  50975. return this._animation;
  50976. },
  50977. enumerable: true,
  50978. configurable: true
  50979. });
  50980. /**
  50981. * Resets the runtime animation to the beginning
  50982. * @param restoreOriginal defines whether to restore the target property to the original value
  50983. */
  50984. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50985. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50986. if (restoreOriginal) {
  50987. if (this._target instanceof Array) {
  50988. var index = 0;
  50989. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50990. var target = _a[_i];
  50991. if (this._originalValue[index] !== undefined) {
  50992. this._setValue(target, this._originalValue[index], -1);
  50993. }
  50994. index++;
  50995. }
  50996. }
  50997. else {
  50998. if (this._originalValue[0] !== undefined) {
  50999. this._setValue(this._target, this._originalValue[0], -1);
  51000. }
  51001. }
  51002. }
  51003. this._offsetsCache = {};
  51004. this._highLimitsCache = {};
  51005. this._currentFrame = 0;
  51006. this._blendingFactor = 0;
  51007. this._originalValue = new Array();
  51008. // Events
  51009. for (var index = 0; index < this._events.length; index++) {
  51010. this._events[index].isDone = false;
  51011. }
  51012. };
  51013. /**
  51014. * Specifies if the runtime animation is stopped
  51015. * @returns Boolean specifying if the runtime animation is stopped
  51016. */
  51017. RuntimeAnimation.prototype.isStopped = function () {
  51018. return this._stopped;
  51019. };
  51020. /**
  51021. * Disposes of the runtime animation
  51022. */
  51023. RuntimeAnimation.prototype.dispose = function () {
  51024. var index = this._animation.runtimeAnimations.indexOf(this);
  51025. if (index > -1) {
  51026. this._animation.runtimeAnimations.splice(index, 1);
  51027. }
  51028. };
  51029. /**
  51030. * Interpolates the animation from the current frame
  51031. * @param currentFrame The frame to interpolate the animation to
  51032. * @param repeatCount The number of times that the animation should loop
  51033. * @param loopMode The type of looping mode to use
  51034. * @param offsetValue Animation offset value
  51035. * @param highLimitValue The high limit value
  51036. * @returns The interpolated value
  51037. */
  51038. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51039. this._currentFrame = currentFrame;
  51040. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51041. this._workValue = BABYLON.Matrix.Zero();
  51042. }
  51043. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51044. };
  51045. /**
  51046. * Apply the interpolated value to the target
  51047. * @param currentValue defines the value computed by the animation
  51048. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51049. */
  51050. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51051. if (weight === void 0) { weight = 1.0; }
  51052. if (this._target instanceof Array) {
  51053. var index = 0;
  51054. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51055. var target = _a[_i];
  51056. this._setValue(target, currentValue, weight, index);
  51057. index++;
  51058. }
  51059. }
  51060. else {
  51061. this._setValue(this._target, currentValue, weight);
  51062. }
  51063. };
  51064. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51065. if (targetIndex === void 0) { targetIndex = 0; }
  51066. // Set value
  51067. var path;
  51068. var destination;
  51069. var targetPropertyPath = this._animation.targetPropertyPath;
  51070. if (targetPropertyPath.length > 1) {
  51071. var property = target[targetPropertyPath[0]];
  51072. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51073. property = property[targetPropertyPath[index]];
  51074. }
  51075. path = targetPropertyPath[targetPropertyPath.length - 1];
  51076. destination = property;
  51077. }
  51078. else {
  51079. path = targetPropertyPath[0];
  51080. destination = target;
  51081. }
  51082. this._targetPath = path;
  51083. this._activeTarget = destination;
  51084. this._weight = weight;
  51085. if (this._originalValue[targetIndex] === undefined) {
  51086. var originalValue = void 0;
  51087. if (destination.getRestPose && path === "_matrix") { // For bones
  51088. originalValue = destination.getRestPose();
  51089. }
  51090. else {
  51091. originalValue = destination[path];
  51092. }
  51093. if (originalValue && originalValue.clone) {
  51094. this._originalValue[targetIndex] = originalValue.clone();
  51095. }
  51096. else {
  51097. this._originalValue[targetIndex] = originalValue;
  51098. }
  51099. }
  51100. // Blending
  51101. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51102. if (enableBlending && this._blendingFactor <= 1.0) {
  51103. if (!this._originalBlendValue) {
  51104. var originalValue = destination[path];
  51105. if (originalValue.clone) {
  51106. this._originalBlendValue = originalValue.clone();
  51107. }
  51108. else {
  51109. this._originalBlendValue = originalValue;
  51110. }
  51111. }
  51112. if (this._originalBlendValue.m) { // Matrix
  51113. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51114. if (this._currentValue) {
  51115. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51116. }
  51117. else {
  51118. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51119. }
  51120. }
  51121. else {
  51122. if (this._currentValue) {
  51123. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51124. }
  51125. else {
  51126. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51127. }
  51128. }
  51129. }
  51130. else {
  51131. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51132. }
  51133. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51134. this._blendingFactor += blendingSpeed;
  51135. }
  51136. else {
  51137. this._currentValue = currentValue;
  51138. }
  51139. if (weight !== -1.0) {
  51140. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51141. }
  51142. else {
  51143. destination[path] = this._currentValue;
  51144. }
  51145. if (target.markAsDirty) {
  51146. target.markAsDirty(this._animation.targetProperty);
  51147. }
  51148. };
  51149. /**
  51150. * Gets the loop pmode of the runtime animation
  51151. * @returns Loop Mode
  51152. */
  51153. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51154. if (this._target && this._target.animationPropertiesOverride) {
  51155. return this._target.animationPropertiesOverride.loopMode;
  51156. }
  51157. return this._animation.loopMode;
  51158. };
  51159. /**
  51160. * Move the current animation to a given frame
  51161. * @param frame defines the frame to move to
  51162. */
  51163. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51164. var keys = this._animation.getKeys();
  51165. if (frame < keys[0].frame) {
  51166. frame = keys[0].frame;
  51167. }
  51168. else if (frame > keys[keys.length - 1].frame) {
  51169. frame = keys[keys.length - 1].frame;
  51170. }
  51171. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51172. this.setValue(currentValue, -1);
  51173. };
  51174. /**
  51175. * @hidden Internal use only
  51176. */
  51177. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51178. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51179. this._ratioOffset = this._previousRatio - newRatio;
  51180. };
  51181. /**
  51182. * Execute the current animation
  51183. * @param delay defines the delay to add to the current frame
  51184. * @param from defines the lower bound of the animation range
  51185. * @param to defines the upper bound of the animation range
  51186. * @param loop defines if the current animation must loop
  51187. * @param speedRatio defines the current speed ratio
  51188. * @param weight defines the weight of the animation (default is -1 so no weight)
  51189. * @returns a boolean indicating if the animation is running
  51190. */
  51191. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51192. if (weight === void 0) { weight = -1.0; }
  51193. var targetPropertyPath = this._animation.targetPropertyPath;
  51194. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51195. this._stopped = true;
  51196. return false;
  51197. }
  51198. var returnValue = true;
  51199. var keys = this._animation.getKeys();
  51200. // Adding a start key at frame 0 if missing
  51201. if (keys[0].frame !== 0) {
  51202. var newKey = { frame: 0, value: keys[0].value };
  51203. keys.splice(0, 0, newKey);
  51204. }
  51205. // Adding a duplicate key when there is only one key at frame zero
  51206. else if (keys.length === 1) {
  51207. var newKey = { frame: 0.001, value: keys[0].value };
  51208. keys.push(newKey);
  51209. }
  51210. // Check limits
  51211. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51212. from = keys[0].frame;
  51213. }
  51214. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51215. to = keys[keys.length - 1].frame;
  51216. }
  51217. //to and from cannot be the same key
  51218. if (from === to) {
  51219. if (from > keys[0].frame) {
  51220. from--;
  51221. }
  51222. else if (to < keys[keys.length - 1].frame) {
  51223. to++;
  51224. }
  51225. }
  51226. // Compute ratio
  51227. var range = to - from;
  51228. var offsetValue;
  51229. // ratio represents the frame delta between from and to
  51230. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51231. var highLimitValue = 0;
  51232. this._previousDelay = delay;
  51233. this._previousRatio = ratio;
  51234. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51235. returnValue = false;
  51236. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51237. }
  51238. else {
  51239. // Get max value if required
  51240. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51241. var keyOffset = to.toString() + from.toString();
  51242. if (!this._offsetsCache[keyOffset]) {
  51243. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51244. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51245. switch (this._animation.dataType) {
  51246. // Float
  51247. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51248. this._offsetsCache[keyOffset] = toValue - fromValue;
  51249. break;
  51250. // Quaternion
  51251. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51252. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51253. break;
  51254. // Vector3
  51255. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51256. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51257. // Vector2
  51258. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51259. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51260. // Size
  51261. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51262. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51263. // Color3
  51264. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51265. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51266. default:
  51267. break;
  51268. }
  51269. this._highLimitsCache[keyOffset] = toValue;
  51270. }
  51271. highLimitValue = this._highLimitsCache[keyOffset];
  51272. offsetValue = this._offsetsCache[keyOffset];
  51273. }
  51274. }
  51275. if (offsetValue === undefined) {
  51276. switch (this._animation.dataType) {
  51277. // Float
  51278. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51279. offsetValue = 0;
  51280. break;
  51281. // Quaternion
  51282. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51283. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51284. break;
  51285. // Vector3
  51286. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51287. offsetValue = BABYLON.Vector3.Zero();
  51288. break;
  51289. // Vector2
  51290. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51291. offsetValue = BABYLON.Vector2.Zero();
  51292. break;
  51293. // Size
  51294. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51295. offsetValue = BABYLON.Size.Zero();
  51296. break;
  51297. // Color3
  51298. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51299. offsetValue = BABYLON.Color3.Black();
  51300. }
  51301. }
  51302. // Compute value
  51303. var repeatCount = (ratio / range) >> 0;
  51304. var currentFrame = returnValue ? from + ratio % range : to;
  51305. // Need to normalize?
  51306. if (this._host && this._host.syncRoot) {
  51307. var syncRoot = this._host.syncRoot;
  51308. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51309. currentFrame = from + (to - from) * hostNormalizedFrame;
  51310. }
  51311. // Reset events if looping
  51312. var events = this._events;
  51313. if (range > 0 && this.currentFrame > currentFrame ||
  51314. range < 0 && this.currentFrame < currentFrame) {
  51315. // Need to reset animation events
  51316. for (var index = 0; index < events.length; index++) {
  51317. if (!events[index].onlyOnce) {
  51318. // reset event, the animation is looping
  51319. events[index].isDone = false;
  51320. }
  51321. }
  51322. }
  51323. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51324. // Set value
  51325. this.setValue(currentValue, weight);
  51326. // Check events
  51327. for (var index = 0; index < events.length; index++) {
  51328. // Make sure current frame has passed event frame and that event frame is within the current range
  51329. // Also, handle both forward and reverse animations
  51330. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51331. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51332. var event = events[index];
  51333. if (!event.isDone) {
  51334. // If event should be done only once, remove it.
  51335. if (event.onlyOnce) {
  51336. events.splice(index, 1);
  51337. index--;
  51338. }
  51339. event.isDone = true;
  51340. event.action(currentFrame);
  51341. } // Don't do anything if the event has already be done.
  51342. }
  51343. }
  51344. if (!returnValue) {
  51345. this._stopped = true;
  51346. }
  51347. return returnValue;
  51348. };
  51349. return RuntimeAnimation;
  51350. }());
  51351. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51352. })(BABYLON || (BABYLON = {}));
  51353. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51354. var BABYLON;
  51355. (function (BABYLON) {
  51356. /**
  51357. * Class used to store an actual running animation
  51358. */
  51359. var Animatable = /** @class */ (function () {
  51360. /**
  51361. * Creates a new Animatable
  51362. * @param scene defines the hosting scene
  51363. * @param target defines the target object
  51364. * @param fromFrame defines the starting frame number (default is 0)
  51365. * @param toFrame defines the ending frame number (default is 100)
  51366. * @param loopAnimation defines if the animation must loop (default is false)
  51367. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51368. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51369. * @param animations defines a group of animation to add to the new Animatable
  51370. */
  51371. function Animatable(scene,
  51372. /** defines the target object */
  51373. target,
  51374. /** defines the starting frame number (default is 0) */
  51375. fromFrame,
  51376. /** defines the ending frame number (default is 100) */
  51377. toFrame,
  51378. /** defines if the animation must loop (default is false) */
  51379. loopAnimation, speedRatio,
  51380. /** defines a callback to call when animation ends if it is not looping */
  51381. onAnimationEnd, animations) {
  51382. if (fromFrame === void 0) { fromFrame = 0; }
  51383. if (toFrame === void 0) { toFrame = 100; }
  51384. if (loopAnimation === void 0) { loopAnimation = false; }
  51385. if (speedRatio === void 0) { speedRatio = 1.0; }
  51386. this.target = target;
  51387. this.fromFrame = fromFrame;
  51388. this.toFrame = toFrame;
  51389. this.loopAnimation = loopAnimation;
  51390. this.onAnimationEnd = onAnimationEnd;
  51391. this._localDelayOffset = null;
  51392. this._pausedDelay = null;
  51393. this._runtimeAnimations = new Array();
  51394. this._paused = false;
  51395. this._speedRatio = 1;
  51396. this._weight = -1.0;
  51397. /**
  51398. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51399. * This will only apply for non looping animation (default is true)
  51400. */
  51401. this.disposeOnEnd = true;
  51402. /**
  51403. * Gets a boolean indicating if the animation has started
  51404. */
  51405. this.animationStarted = false;
  51406. /**
  51407. * Observer raised when the animation ends
  51408. */
  51409. this.onAnimationEndObservable = new BABYLON.Observable();
  51410. this._scene = scene;
  51411. if (animations) {
  51412. this.appendAnimations(target, animations);
  51413. }
  51414. this._speedRatio = speedRatio;
  51415. scene._activeAnimatables.push(this);
  51416. }
  51417. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51418. /**
  51419. * Gets the root Animatable used to synchronize and normalize animations
  51420. */
  51421. get: function () {
  51422. return this._syncRoot;
  51423. },
  51424. enumerable: true,
  51425. configurable: true
  51426. });
  51427. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51428. /**
  51429. * Gets the current frame of the first RuntimeAnimation
  51430. * Used to synchronize Animatables
  51431. */
  51432. get: function () {
  51433. if (this._runtimeAnimations.length === 0) {
  51434. return 0;
  51435. }
  51436. return this._runtimeAnimations[0].currentFrame;
  51437. },
  51438. enumerable: true,
  51439. configurable: true
  51440. });
  51441. Object.defineProperty(Animatable.prototype, "weight", {
  51442. /**
  51443. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51444. */
  51445. get: function () {
  51446. return this._weight;
  51447. },
  51448. set: function (value) {
  51449. if (value === -1) { // -1 is ok and means no weight
  51450. this._weight = -1;
  51451. return;
  51452. }
  51453. // Else weight must be in [0, 1] range
  51454. this._weight = Math.min(Math.max(value, 0), 1.0);
  51455. },
  51456. enumerable: true,
  51457. configurable: true
  51458. });
  51459. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51460. /**
  51461. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51462. */
  51463. get: function () {
  51464. return this._speedRatio;
  51465. },
  51466. set: function (value) {
  51467. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51468. var animation = this._runtimeAnimations[index];
  51469. animation._prepareForSpeedRatioChange(value);
  51470. }
  51471. this._speedRatio = value;
  51472. },
  51473. enumerable: true,
  51474. configurable: true
  51475. });
  51476. // Methods
  51477. /**
  51478. * Synchronize and normalize current Animatable with a source Animatable
  51479. * This is useful when using animation weights and when animations are not of the same length
  51480. * @param root defines the root Animatable to synchronize with
  51481. * @returns the current Animatable
  51482. */
  51483. Animatable.prototype.syncWith = function (root) {
  51484. this._syncRoot = root;
  51485. if (root) {
  51486. // Make sure this animatable will animate after the root
  51487. var index = this._scene._activeAnimatables.indexOf(this);
  51488. if (index > -1) {
  51489. this._scene._activeAnimatables.splice(index, 1);
  51490. this._scene._activeAnimatables.push(this);
  51491. }
  51492. }
  51493. return this;
  51494. };
  51495. /**
  51496. * Gets the list of runtime animations
  51497. * @returns an array of RuntimeAnimation
  51498. */
  51499. Animatable.prototype.getAnimations = function () {
  51500. return this._runtimeAnimations;
  51501. };
  51502. /**
  51503. * Adds more animations to the current animatable
  51504. * @param target defines the target of the animations
  51505. * @param animations defines the new animations to add
  51506. */
  51507. Animatable.prototype.appendAnimations = function (target, animations) {
  51508. for (var index = 0; index < animations.length; index++) {
  51509. var animation = animations[index];
  51510. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51511. }
  51512. };
  51513. /**
  51514. * Gets the source animation for a specific property
  51515. * @param property defines the propertyu to look for
  51516. * @returns null or the source animation for the given property
  51517. */
  51518. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51519. var runtimeAnimations = this._runtimeAnimations;
  51520. for (var index = 0; index < runtimeAnimations.length; index++) {
  51521. if (runtimeAnimations[index].animation.targetProperty === property) {
  51522. return runtimeAnimations[index].animation;
  51523. }
  51524. }
  51525. return null;
  51526. };
  51527. /**
  51528. * Gets the runtime animation for a specific property
  51529. * @param property defines the propertyu to look for
  51530. * @returns null or the runtime animation for the given property
  51531. */
  51532. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51533. var runtimeAnimations = this._runtimeAnimations;
  51534. for (var index = 0; index < runtimeAnimations.length; index++) {
  51535. if (runtimeAnimations[index].animation.targetProperty === property) {
  51536. return runtimeAnimations[index];
  51537. }
  51538. }
  51539. return null;
  51540. };
  51541. /**
  51542. * Resets the animatable to its original state
  51543. */
  51544. Animatable.prototype.reset = function () {
  51545. var runtimeAnimations = this._runtimeAnimations;
  51546. for (var index = 0; index < runtimeAnimations.length; index++) {
  51547. runtimeAnimations[index].reset(true);
  51548. }
  51549. this._localDelayOffset = null;
  51550. this._pausedDelay = null;
  51551. };
  51552. /**
  51553. * Allows the animatable to blend with current running animations
  51554. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51555. * @param blendingSpeed defines the blending speed to use
  51556. */
  51557. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51558. var runtimeAnimations = this._runtimeAnimations;
  51559. for (var index = 0; index < runtimeAnimations.length; index++) {
  51560. runtimeAnimations[index].animation.enableBlending = true;
  51561. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51562. }
  51563. };
  51564. /**
  51565. * Disable animation blending
  51566. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51567. */
  51568. Animatable.prototype.disableBlending = function () {
  51569. var runtimeAnimations = this._runtimeAnimations;
  51570. for (var index = 0; index < runtimeAnimations.length; index++) {
  51571. runtimeAnimations[index].animation.enableBlending = false;
  51572. }
  51573. };
  51574. /**
  51575. * Jump directly to a given frame
  51576. * @param frame defines the frame to jump to
  51577. */
  51578. Animatable.prototype.goToFrame = function (frame) {
  51579. var runtimeAnimations = this._runtimeAnimations;
  51580. if (runtimeAnimations[0]) {
  51581. var fps = runtimeAnimations[0].animation.framePerSecond;
  51582. var currentFrame = runtimeAnimations[0].currentFrame;
  51583. var adjustTime = frame - currentFrame;
  51584. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51585. if (this._localDelayOffset === null) {
  51586. this._localDelayOffset = 0;
  51587. }
  51588. this._localDelayOffset -= delay;
  51589. }
  51590. for (var index = 0; index < runtimeAnimations.length; index++) {
  51591. runtimeAnimations[index].goToFrame(frame);
  51592. }
  51593. };
  51594. /**
  51595. * Pause the animation
  51596. */
  51597. Animatable.prototype.pause = function () {
  51598. if (this._paused) {
  51599. return;
  51600. }
  51601. this._paused = true;
  51602. };
  51603. /**
  51604. * Restart the animation
  51605. */
  51606. Animatable.prototype.restart = function () {
  51607. this._paused = false;
  51608. };
  51609. Animatable.prototype._raiseOnAnimationEnd = function () {
  51610. if (this.onAnimationEnd) {
  51611. this.onAnimationEnd();
  51612. }
  51613. this.onAnimationEndObservable.notifyObservers(this);
  51614. };
  51615. /**
  51616. * Stop and delete the current animation
  51617. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51618. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51619. */
  51620. Animatable.prototype.stop = function (animationName, targetMask) {
  51621. if (animationName || targetMask) {
  51622. var idx = this._scene._activeAnimatables.indexOf(this);
  51623. if (idx > -1) {
  51624. var runtimeAnimations = this._runtimeAnimations;
  51625. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51626. var runtimeAnimation = runtimeAnimations[index];
  51627. if (animationName && runtimeAnimation.animation.name != animationName) {
  51628. continue;
  51629. }
  51630. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51631. continue;
  51632. }
  51633. runtimeAnimation.dispose();
  51634. runtimeAnimations.splice(index, 1);
  51635. }
  51636. if (runtimeAnimations.length == 0) {
  51637. this._scene._activeAnimatables.splice(idx, 1);
  51638. this._raiseOnAnimationEnd();
  51639. }
  51640. }
  51641. }
  51642. else {
  51643. var index = this._scene._activeAnimatables.indexOf(this);
  51644. if (index > -1) {
  51645. this._scene._activeAnimatables.splice(index, 1);
  51646. var runtimeAnimations = this._runtimeAnimations;
  51647. for (var index = 0; index < runtimeAnimations.length; index++) {
  51648. runtimeAnimations[index].dispose();
  51649. }
  51650. this._raiseOnAnimationEnd();
  51651. }
  51652. }
  51653. };
  51654. /**
  51655. * Wait asynchronously for the animation to end
  51656. * @returns a promise which will be fullfilled when the animation ends
  51657. */
  51658. Animatable.prototype.waitAsync = function () {
  51659. var _this = this;
  51660. return new Promise(function (resolve, reject) {
  51661. _this.onAnimationEndObservable.add(function () {
  51662. resolve(_this);
  51663. }, undefined, undefined, _this, true);
  51664. });
  51665. };
  51666. /** @hidden */
  51667. Animatable.prototype._animate = function (delay) {
  51668. if (this._paused) {
  51669. this.animationStarted = false;
  51670. if (this._pausedDelay === null) {
  51671. this._pausedDelay = delay;
  51672. }
  51673. return true;
  51674. }
  51675. if (this._localDelayOffset === null) {
  51676. this._localDelayOffset = delay;
  51677. this._pausedDelay = null;
  51678. }
  51679. else if (this._pausedDelay !== null) {
  51680. this._localDelayOffset += delay - this._pausedDelay;
  51681. this._pausedDelay = null;
  51682. }
  51683. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51684. return true;
  51685. }
  51686. // Animating
  51687. var running = false;
  51688. var runtimeAnimations = this._runtimeAnimations;
  51689. var index;
  51690. for (index = 0; index < runtimeAnimations.length; index++) {
  51691. var animation = runtimeAnimations[index];
  51692. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51693. running = running || isRunning;
  51694. }
  51695. this.animationStarted = running;
  51696. if (!running) {
  51697. if (this.disposeOnEnd) {
  51698. // Remove from active animatables
  51699. index = this._scene._activeAnimatables.indexOf(this);
  51700. this._scene._activeAnimatables.splice(index, 1);
  51701. // Dispose all runtime animations
  51702. for (index = 0; index < runtimeAnimations.length; index++) {
  51703. runtimeAnimations[index].dispose();
  51704. }
  51705. }
  51706. this._raiseOnAnimationEnd();
  51707. if (this.disposeOnEnd) {
  51708. this.onAnimationEnd = null;
  51709. this.onAnimationEndObservable.clear();
  51710. }
  51711. }
  51712. return running;
  51713. };
  51714. return Animatable;
  51715. }());
  51716. BABYLON.Animatable = Animatable;
  51717. })(BABYLON || (BABYLON = {}));
  51718. //# sourceMappingURL=babylon.animatable.js.map
  51719. var BABYLON;
  51720. (function (BABYLON) {
  51721. var EasingFunction = /** @class */ (function () {
  51722. function EasingFunction() {
  51723. // Properties
  51724. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51725. }
  51726. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51727. get: function () {
  51728. return EasingFunction._EASINGMODE_EASEIN;
  51729. },
  51730. enumerable: true,
  51731. configurable: true
  51732. });
  51733. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51734. get: function () {
  51735. return EasingFunction._EASINGMODE_EASEOUT;
  51736. },
  51737. enumerable: true,
  51738. configurable: true
  51739. });
  51740. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51741. get: function () {
  51742. return EasingFunction._EASINGMODE_EASEINOUT;
  51743. },
  51744. enumerable: true,
  51745. configurable: true
  51746. });
  51747. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51748. var n = Math.min(Math.max(easingMode, 0), 2);
  51749. this._easingMode = n;
  51750. };
  51751. EasingFunction.prototype.getEasingMode = function () {
  51752. return this._easingMode;
  51753. };
  51754. EasingFunction.prototype.easeInCore = function (gradient) {
  51755. throw new Error('You must implement this method');
  51756. };
  51757. EasingFunction.prototype.ease = function (gradient) {
  51758. switch (this._easingMode) {
  51759. case EasingFunction.EASINGMODE_EASEIN:
  51760. return this.easeInCore(gradient);
  51761. case EasingFunction.EASINGMODE_EASEOUT:
  51762. return (1 - this.easeInCore(1 - gradient));
  51763. }
  51764. if (gradient >= 0.5) {
  51765. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51766. }
  51767. return (this.easeInCore(gradient * 2) * 0.5);
  51768. };
  51769. //Statics
  51770. EasingFunction._EASINGMODE_EASEIN = 0;
  51771. EasingFunction._EASINGMODE_EASEOUT = 1;
  51772. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51773. return EasingFunction;
  51774. }());
  51775. BABYLON.EasingFunction = EasingFunction;
  51776. var CircleEase = /** @class */ (function (_super) {
  51777. __extends(CircleEase, _super);
  51778. function CircleEase() {
  51779. return _super !== null && _super.apply(this, arguments) || this;
  51780. }
  51781. CircleEase.prototype.easeInCore = function (gradient) {
  51782. gradient = Math.max(0, Math.min(1, gradient));
  51783. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51784. };
  51785. return CircleEase;
  51786. }(EasingFunction));
  51787. BABYLON.CircleEase = CircleEase;
  51788. var BackEase = /** @class */ (function (_super) {
  51789. __extends(BackEase, _super);
  51790. function BackEase(amplitude) {
  51791. if (amplitude === void 0) { amplitude = 1; }
  51792. var _this = _super.call(this) || this;
  51793. _this.amplitude = amplitude;
  51794. return _this;
  51795. }
  51796. BackEase.prototype.easeInCore = function (gradient) {
  51797. var num = Math.max(0, this.amplitude);
  51798. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51799. };
  51800. return BackEase;
  51801. }(EasingFunction));
  51802. BABYLON.BackEase = BackEase;
  51803. var BounceEase = /** @class */ (function (_super) {
  51804. __extends(BounceEase, _super);
  51805. function BounceEase(bounces, bounciness) {
  51806. if (bounces === void 0) { bounces = 3; }
  51807. if (bounciness === void 0) { bounciness = 2; }
  51808. var _this = _super.call(this) || this;
  51809. _this.bounces = bounces;
  51810. _this.bounciness = bounciness;
  51811. return _this;
  51812. }
  51813. BounceEase.prototype.easeInCore = function (gradient) {
  51814. var y = Math.max(0.0, this.bounces);
  51815. var bounciness = this.bounciness;
  51816. if (bounciness <= 1.0) {
  51817. bounciness = 1.001;
  51818. }
  51819. var num9 = Math.pow(bounciness, y);
  51820. var num5 = 1.0 - bounciness;
  51821. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51822. var num15 = gradient * num4;
  51823. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51824. var num3 = Math.floor(num65);
  51825. var num13 = num3 + 1.0;
  51826. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51827. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51828. var num7 = (num8 + num12) * 0.5;
  51829. var num6 = gradient - num7;
  51830. var num2 = num7 - num8;
  51831. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51832. };
  51833. return BounceEase;
  51834. }(EasingFunction));
  51835. BABYLON.BounceEase = BounceEase;
  51836. var CubicEase = /** @class */ (function (_super) {
  51837. __extends(CubicEase, _super);
  51838. function CubicEase() {
  51839. return _super !== null && _super.apply(this, arguments) || this;
  51840. }
  51841. CubicEase.prototype.easeInCore = function (gradient) {
  51842. return (gradient * gradient * gradient);
  51843. };
  51844. return CubicEase;
  51845. }(EasingFunction));
  51846. BABYLON.CubicEase = CubicEase;
  51847. var ElasticEase = /** @class */ (function (_super) {
  51848. __extends(ElasticEase, _super);
  51849. function ElasticEase(oscillations, springiness) {
  51850. if (oscillations === void 0) { oscillations = 3; }
  51851. if (springiness === void 0) { springiness = 3; }
  51852. var _this = _super.call(this) || this;
  51853. _this.oscillations = oscillations;
  51854. _this.springiness = springiness;
  51855. return _this;
  51856. }
  51857. ElasticEase.prototype.easeInCore = function (gradient) {
  51858. var num2;
  51859. var num3 = Math.max(0.0, this.oscillations);
  51860. var num = Math.max(0.0, this.springiness);
  51861. if (num == 0) {
  51862. num2 = gradient;
  51863. }
  51864. else {
  51865. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51866. }
  51867. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51868. };
  51869. return ElasticEase;
  51870. }(EasingFunction));
  51871. BABYLON.ElasticEase = ElasticEase;
  51872. var ExponentialEase = /** @class */ (function (_super) {
  51873. __extends(ExponentialEase, _super);
  51874. function ExponentialEase(exponent) {
  51875. if (exponent === void 0) { exponent = 2; }
  51876. var _this = _super.call(this) || this;
  51877. _this.exponent = exponent;
  51878. return _this;
  51879. }
  51880. ExponentialEase.prototype.easeInCore = function (gradient) {
  51881. if (this.exponent <= 0) {
  51882. return gradient;
  51883. }
  51884. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51885. };
  51886. return ExponentialEase;
  51887. }(EasingFunction));
  51888. BABYLON.ExponentialEase = ExponentialEase;
  51889. var PowerEase = /** @class */ (function (_super) {
  51890. __extends(PowerEase, _super);
  51891. function PowerEase(power) {
  51892. if (power === void 0) { power = 2; }
  51893. var _this = _super.call(this) || this;
  51894. _this.power = power;
  51895. return _this;
  51896. }
  51897. PowerEase.prototype.easeInCore = function (gradient) {
  51898. var y = Math.max(0.0, this.power);
  51899. return Math.pow(gradient, y);
  51900. };
  51901. return PowerEase;
  51902. }(EasingFunction));
  51903. BABYLON.PowerEase = PowerEase;
  51904. var QuadraticEase = /** @class */ (function (_super) {
  51905. __extends(QuadraticEase, _super);
  51906. function QuadraticEase() {
  51907. return _super !== null && _super.apply(this, arguments) || this;
  51908. }
  51909. QuadraticEase.prototype.easeInCore = function (gradient) {
  51910. return (gradient * gradient);
  51911. };
  51912. return QuadraticEase;
  51913. }(EasingFunction));
  51914. BABYLON.QuadraticEase = QuadraticEase;
  51915. var QuarticEase = /** @class */ (function (_super) {
  51916. __extends(QuarticEase, _super);
  51917. function QuarticEase() {
  51918. return _super !== null && _super.apply(this, arguments) || this;
  51919. }
  51920. QuarticEase.prototype.easeInCore = function (gradient) {
  51921. return (gradient * gradient * gradient * gradient);
  51922. };
  51923. return QuarticEase;
  51924. }(EasingFunction));
  51925. BABYLON.QuarticEase = QuarticEase;
  51926. var QuinticEase = /** @class */ (function (_super) {
  51927. __extends(QuinticEase, _super);
  51928. function QuinticEase() {
  51929. return _super !== null && _super.apply(this, arguments) || this;
  51930. }
  51931. QuinticEase.prototype.easeInCore = function (gradient) {
  51932. return (gradient * gradient * gradient * gradient * gradient);
  51933. };
  51934. return QuinticEase;
  51935. }(EasingFunction));
  51936. BABYLON.QuinticEase = QuinticEase;
  51937. var SineEase = /** @class */ (function (_super) {
  51938. __extends(SineEase, _super);
  51939. function SineEase() {
  51940. return _super !== null && _super.apply(this, arguments) || this;
  51941. }
  51942. SineEase.prototype.easeInCore = function (gradient) {
  51943. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51944. };
  51945. return SineEase;
  51946. }(EasingFunction));
  51947. BABYLON.SineEase = SineEase;
  51948. var BezierCurveEase = /** @class */ (function (_super) {
  51949. __extends(BezierCurveEase, _super);
  51950. function BezierCurveEase(x1, y1, x2, y2) {
  51951. if (x1 === void 0) { x1 = 0; }
  51952. if (y1 === void 0) { y1 = 0; }
  51953. if (x2 === void 0) { x2 = 1; }
  51954. if (y2 === void 0) { y2 = 1; }
  51955. var _this = _super.call(this) || this;
  51956. _this.x1 = x1;
  51957. _this.y1 = y1;
  51958. _this.x2 = x2;
  51959. _this.y2 = y2;
  51960. return _this;
  51961. }
  51962. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51963. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51964. };
  51965. return BezierCurveEase;
  51966. }(EasingFunction));
  51967. BABYLON.BezierCurveEase = BezierCurveEase;
  51968. })(BABYLON || (BABYLON = {}));
  51969. //# sourceMappingURL=babylon.easing.js.map
  51970. var BABYLON;
  51971. (function (BABYLON) {
  51972. /**
  51973. * A Condition applied to an Action
  51974. */
  51975. var Condition = /** @class */ (function () {
  51976. /**
  51977. * Creates a new Condition
  51978. * @param actionManager the manager of the action the condition is applied to
  51979. */
  51980. function Condition(actionManager) {
  51981. this._actionManager = actionManager;
  51982. }
  51983. /**
  51984. * Check if the current condition is valid
  51985. * @returns a boolean
  51986. */
  51987. Condition.prototype.isValid = function () {
  51988. return true;
  51989. };
  51990. /**
  51991. * Internal only
  51992. * @hidden
  51993. */
  51994. Condition.prototype._getProperty = function (propertyPath) {
  51995. return this._actionManager._getProperty(propertyPath);
  51996. };
  51997. /**
  51998. * Internal only
  51999. * @hidden
  52000. */
  52001. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52002. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52003. };
  52004. /**
  52005. * Serialize placeholder for child classes
  52006. * @returns the serialized object
  52007. */
  52008. Condition.prototype.serialize = function () {
  52009. };
  52010. /**
  52011. * Internal only
  52012. * @hidden
  52013. */
  52014. Condition.prototype._serialize = function (serializedCondition) {
  52015. return {
  52016. type: 2,
  52017. children: [],
  52018. name: serializedCondition.name,
  52019. properties: serializedCondition.properties
  52020. };
  52021. };
  52022. return Condition;
  52023. }());
  52024. BABYLON.Condition = Condition;
  52025. /**
  52026. * Defines specific conditional operators as extensions of Condition
  52027. */
  52028. var ValueCondition = /** @class */ (function (_super) {
  52029. __extends(ValueCondition, _super);
  52030. /**
  52031. * Creates a new ValueCondition
  52032. * @param actionManager manager for the action the condition applies to
  52033. * @param target for the action
  52034. * @param propertyPath path to specify the property of the target the conditional operator uses
  52035. * @param value the value compared by the conditional operator against the current value of the property
  52036. * @param operator the conditional operator, default ValueCondition.IsEqual
  52037. */
  52038. function ValueCondition(actionManager, target,
  52039. /** path to specify the property of the target the conditional operator uses */
  52040. propertyPath,
  52041. /** the value compared by the conditional operator against the current value of the property */
  52042. value,
  52043. /** the conditional operator, default ValueCondition.IsEqual */
  52044. operator) {
  52045. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52046. var _this = _super.call(this, actionManager) || this;
  52047. _this.propertyPath = propertyPath;
  52048. _this.value = value;
  52049. _this.operator = operator;
  52050. _this._target = target;
  52051. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52052. _this._property = _this._getProperty(_this.propertyPath);
  52053. return _this;
  52054. }
  52055. Object.defineProperty(ValueCondition, "IsEqual", {
  52056. /**
  52057. * returns the number for IsEqual
  52058. */
  52059. get: function () {
  52060. return ValueCondition._IsEqual;
  52061. },
  52062. enumerable: true,
  52063. configurable: true
  52064. });
  52065. Object.defineProperty(ValueCondition, "IsDifferent", {
  52066. /**
  52067. * Returns the number for IsDifferent
  52068. */
  52069. get: function () {
  52070. return ValueCondition._IsDifferent;
  52071. },
  52072. enumerable: true,
  52073. configurable: true
  52074. });
  52075. Object.defineProperty(ValueCondition, "IsGreater", {
  52076. /**
  52077. * Returns the number for IsGreater
  52078. */
  52079. get: function () {
  52080. return ValueCondition._IsGreater;
  52081. },
  52082. enumerable: true,
  52083. configurable: true
  52084. });
  52085. Object.defineProperty(ValueCondition, "IsLesser", {
  52086. /**
  52087. * Returns the number for IsLesser
  52088. */
  52089. get: function () {
  52090. return ValueCondition._IsLesser;
  52091. },
  52092. enumerable: true,
  52093. configurable: true
  52094. });
  52095. /**
  52096. * Compares the given value with the property value for the specified conditional operator
  52097. * @returns the result of the comparison
  52098. */
  52099. ValueCondition.prototype.isValid = function () {
  52100. switch (this.operator) {
  52101. case ValueCondition.IsGreater:
  52102. return this._effectiveTarget[this._property] > this.value;
  52103. case ValueCondition.IsLesser:
  52104. return this._effectiveTarget[this._property] < this.value;
  52105. case ValueCondition.IsEqual:
  52106. case ValueCondition.IsDifferent:
  52107. var check;
  52108. if (this.value.equals) {
  52109. check = this.value.equals(this._effectiveTarget[this._property]);
  52110. }
  52111. else {
  52112. check = this.value === this._effectiveTarget[this._property];
  52113. }
  52114. return this.operator === ValueCondition.IsEqual ? check : !check;
  52115. }
  52116. return false;
  52117. };
  52118. /**
  52119. * Serialize the ValueCondition into a JSON compatible object
  52120. * @returns serialization object
  52121. */
  52122. ValueCondition.prototype.serialize = function () {
  52123. return this._serialize({
  52124. name: "ValueCondition",
  52125. properties: [
  52126. BABYLON.Action._GetTargetProperty(this._target),
  52127. { name: "propertyPath", value: this.propertyPath },
  52128. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52129. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52130. ]
  52131. });
  52132. };
  52133. /**
  52134. * Gets the name of the conditional operator for the ValueCondition
  52135. * @param operator the conditional operator
  52136. * @returns the name
  52137. */
  52138. ValueCondition.GetOperatorName = function (operator) {
  52139. switch (operator) {
  52140. case ValueCondition._IsEqual: return "IsEqual";
  52141. case ValueCondition._IsDifferent: return "IsDifferent";
  52142. case ValueCondition._IsGreater: return "IsGreater";
  52143. case ValueCondition._IsLesser: return "IsLesser";
  52144. default: return "";
  52145. }
  52146. };
  52147. /**
  52148. * Internal only
  52149. * @hidden
  52150. */
  52151. ValueCondition._IsEqual = 0;
  52152. /**
  52153. * Internal only
  52154. * @hidden
  52155. */
  52156. ValueCondition._IsDifferent = 1;
  52157. /**
  52158. * Internal only
  52159. * @hidden
  52160. */
  52161. ValueCondition._IsGreater = 2;
  52162. /**
  52163. * Internal only
  52164. * @hidden
  52165. */
  52166. ValueCondition._IsLesser = 3;
  52167. return ValueCondition;
  52168. }(Condition));
  52169. BABYLON.ValueCondition = ValueCondition;
  52170. /**
  52171. * Defines a predicate condition as an extension of Condition
  52172. */
  52173. var PredicateCondition = /** @class */ (function (_super) {
  52174. __extends(PredicateCondition, _super);
  52175. /**
  52176. * Creates a new PredicateCondition
  52177. * @param actionManager manager for the action the condition applies to
  52178. * @param predicate defines the predicate function used to validate the condition
  52179. */
  52180. function PredicateCondition(actionManager,
  52181. /** defines the predicate function used to validate the condition */
  52182. predicate) {
  52183. var _this = _super.call(this, actionManager) || this;
  52184. _this.predicate = predicate;
  52185. return _this;
  52186. }
  52187. /**
  52188. * @returns the validity of the predicate condition
  52189. */
  52190. PredicateCondition.prototype.isValid = function () {
  52191. return this.predicate();
  52192. };
  52193. return PredicateCondition;
  52194. }(Condition));
  52195. BABYLON.PredicateCondition = PredicateCondition;
  52196. /**
  52197. * Defines a state condition as an extension of Condition
  52198. */
  52199. var StateCondition = /** @class */ (function (_super) {
  52200. __extends(StateCondition, _super);
  52201. /**
  52202. * Creates a new StateCondition
  52203. * @param actionManager manager for the action the condition applies to
  52204. * @param target of the condition
  52205. * @param value to compare with target state
  52206. */
  52207. function StateCondition(actionManager, target, value) {
  52208. var _this = _super.call(this, actionManager) || this;
  52209. _this.value = value;
  52210. _this._target = target;
  52211. return _this;
  52212. }
  52213. /**
  52214. * @returns the validity of the state
  52215. */
  52216. StateCondition.prototype.isValid = function () {
  52217. return this._target.state === this.value;
  52218. };
  52219. /**
  52220. * Serialize the StateCondition into a JSON compatible object
  52221. * @returns serialization object
  52222. */
  52223. StateCondition.prototype.serialize = function () {
  52224. return this._serialize({
  52225. name: "StateCondition",
  52226. properties: [
  52227. BABYLON.Action._GetTargetProperty(this._target),
  52228. { name: "value", value: this.value }
  52229. ]
  52230. });
  52231. };
  52232. return StateCondition;
  52233. }(Condition));
  52234. BABYLON.StateCondition = StateCondition;
  52235. })(BABYLON || (BABYLON = {}));
  52236. //# sourceMappingURL=babylon.condition.js.map
  52237. var BABYLON;
  52238. (function (BABYLON) {
  52239. /**
  52240. * The action to be carried out following a trigger
  52241. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52242. */
  52243. var Action = /** @class */ (function () {
  52244. /**
  52245. * Creates a new Action
  52246. * @param triggerOptions the trigger, with or without parameters, for the action
  52247. * @param condition an optional determinant of action
  52248. */
  52249. function Action(
  52250. /** the trigger, with or without parameters, for the action */
  52251. triggerOptions, condition) {
  52252. this.triggerOptions = triggerOptions;
  52253. /**
  52254. * An event triggered prior to action being executed.
  52255. */
  52256. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52257. if (triggerOptions.parameter) {
  52258. this.trigger = triggerOptions.trigger;
  52259. this._triggerParameter = triggerOptions.parameter;
  52260. }
  52261. else {
  52262. this.trigger = triggerOptions;
  52263. }
  52264. this._nextActiveAction = this;
  52265. this._condition = condition;
  52266. }
  52267. /**
  52268. * Internal only
  52269. * @hidden
  52270. */
  52271. Action.prototype._prepare = function () {
  52272. };
  52273. /**
  52274. * Gets the trigger parameters
  52275. * @returns the trigger parameters
  52276. */
  52277. Action.prototype.getTriggerParameter = function () {
  52278. return this._triggerParameter;
  52279. };
  52280. /**
  52281. * Internal only - executes current action event
  52282. * @hidden
  52283. */
  52284. Action.prototype._executeCurrent = function (evt) {
  52285. if (this._nextActiveAction._condition) {
  52286. var condition = this._nextActiveAction._condition;
  52287. var currentRenderId = this._actionManager.getScene().getRenderId();
  52288. // We cache the current evaluation for the current frame
  52289. if (condition._evaluationId === currentRenderId) {
  52290. if (!condition._currentResult) {
  52291. return;
  52292. }
  52293. }
  52294. else {
  52295. condition._evaluationId = currentRenderId;
  52296. if (!condition.isValid()) {
  52297. condition._currentResult = false;
  52298. return;
  52299. }
  52300. condition._currentResult = true;
  52301. }
  52302. }
  52303. this.onBeforeExecuteObservable.notifyObservers(this);
  52304. this._nextActiveAction.execute(evt);
  52305. this.skipToNextActiveAction();
  52306. };
  52307. /**
  52308. * Execute placeholder for child classes
  52309. * @param evt optional action event
  52310. */
  52311. Action.prototype.execute = function (evt) {
  52312. };
  52313. /**
  52314. * Skips to next active action
  52315. */
  52316. Action.prototype.skipToNextActiveAction = function () {
  52317. if (this._nextActiveAction._child) {
  52318. if (!this._nextActiveAction._child._actionManager) {
  52319. this._nextActiveAction._child._actionManager = this._actionManager;
  52320. }
  52321. this._nextActiveAction = this._nextActiveAction._child;
  52322. }
  52323. else {
  52324. this._nextActiveAction = this;
  52325. }
  52326. };
  52327. /**
  52328. * Adds action to chain of actions, may be a DoNothingAction
  52329. * @param action defines the next action to execute
  52330. * @returns The action passed in
  52331. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52332. */
  52333. Action.prototype.then = function (action) {
  52334. this._child = action;
  52335. action._actionManager = this._actionManager;
  52336. action._prepare();
  52337. return action;
  52338. };
  52339. /**
  52340. * Internal only
  52341. * @hidden
  52342. */
  52343. Action.prototype._getProperty = function (propertyPath) {
  52344. return this._actionManager._getProperty(propertyPath);
  52345. };
  52346. /**
  52347. * Internal only
  52348. * @hidden
  52349. */
  52350. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52351. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52352. };
  52353. /**
  52354. * Serialize placeholder for child classes
  52355. * @param parent of child
  52356. * @returns the serialized object
  52357. */
  52358. Action.prototype.serialize = function (parent) {
  52359. };
  52360. /**
  52361. * Internal only called by serialize
  52362. * @hidden
  52363. */
  52364. Action.prototype._serialize = function (serializedAction, parent) {
  52365. var serializationObject = {
  52366. type: 1,
  52367. children: [],
  52368. name: serializedAction.name,
  52369. properties: serializedAction.properties || []
  52370. };
  52371. // Serialize child
  52372. if (this._child) {
  52373. this._child.serialize(serializationObject);
  52374. }
  52375. // Check if "this" has a condition
  52376. if (this._condition) {
  52377. var serializedCondition = this._condition.serialize();
  52378. serializedCondition.children.push(serializationObject);
  52379. if (parent) {
  52380. parent.children.push(serializedCondition);
  52381. }
  52382. return serializedCondition;
  52383. }
  52384. if (parent) {
  52385. parent.children.push(serializationObject);
  52386. }
  52387. return serializationObject;
  52388. };
  52389. /**
  52390. * Internal only
  52391. * @hidden
  52392. */
  52393. Action._SerializeValueAsString = function (value) {
  52394. if (typeof value === "number") {
  52395. return value.toString();
  52396. }
  52397. if (typeof value === "boolean") {
  52398. return value ? "true" : "false";
  52399. }
  52400. if (value instanceof BABYLON.Vector2) {
  52401. return value.x + ", " + value.y;
  52402. }
  52403. if (value instanceof BABYLON.Vector3) {
  52404. return value.x + ", " + value.y + ", " + value.z;
  52405. }
  52406. if (value instanceof BABYLON.Color3) {
  52407. return value.r + ", " + value.g + ", " + value.b;
  52408. }
  52409. if (value instanceof BABYLON.Color4) {
  52410. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52411. }
  52412. return value; // string
  52413. };
  52414. /**
  52415. * Internal only
  52416. * @hidden
  52417. */
  52418. Action._GetTargetProperty = function (target) {
  52419. return {
  52420. name: "target",
  52421. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52422. : target instanceof BABYLON.Light ? "LightProperties"
  52423. : target instanceof BABYLON.Camera ? "CameraProperties"
  52424. : "SceneProperties",
  52425. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52426. };
  52427. };
  52428. return Action;
  52429. }());
  52430. BABYLON.Action = Action;
  52431. })(BABYLON || (BABYLON = {}));
  52432. //# sourceMappingURL=babylon.action.js.map
  52433. var BABYLON;
  52434. (function (BABYLON) {
  52435. /**
  52436. * ActionEvent is the event being sent when an action is triggered.
  52437. */
  52438. var ActionEvent = /** @class */ (function () {
  52439. /**
  52440. * Creates a new ActionEvent
  52441. * @param source The mesh or sprite that triggered the action
  52442. * @param pointerX The X mouse cursor position at the time of the event
  52443. * @param pointerY The Y mouse cursor position at the time of the event
  52444. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52445. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52446. * @param additionalData additional data for the event
  52447. */
  52448. function ActionEvent(
  52449. /** The mesh or sprite that triggered the action */
  52450. source,
  52451. /** The X mouse cursor position at the time of the event */
  52452. pointerX,
  52453. /** The Y mouse cursor position at the time of the event */
  52454. pointerY,
  52455. /** The mesh that is currently pointed at (can be null) */
  52456. meshUnderPointer,
  52457. /** the original (browser) event that triggered the ActionEvent */
  52458. sourceEvent,
  52459. /** additional data for the event */
  52460. additionalData) {
  52461. this.source = source;
  52462. this.pointerX = pointerX;
  52463. this.pointerY = pointerY;
  52464. this.meshUnderPointer = meshUnderPointer;
  52465. this.sourceEvent = sourceEvent;
  52466. this.additionalData = additionalData;
  52467. }
  52468. /**
  52469. * Helper function to auto-create an ActionEvent from a source mesh.
  52470. * @param source The source mesh that triggered the event
  52471. * @param evt The original (browser) event
  52472. * @param additionalData additional data for the event
  52473. * @returns the new ActionEvent
  52474. */
  52475. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52476. var scene = source.getScene();
  52477. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52478. };
  52479. /**
  52480. * Helper function to auto-create an ActionEvent from a source sprite
  52481. * @param source The source sprite that triggered the event
  52482. * @param scene Scene associated with the sprite
  52483. * @param evt The original (browser) event
  52484. * @param additionalData additional data for the event
  52485. * @returns the new ActionEvent
  52486. */
  52487. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52488. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52489. };
  52490. /**
  52491. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52492. * @param scene the scene where the event occurred
  52493. * @param evt The original (browser) event
  52494. * @returns the new ActionEvent
  52495. */
  52496. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52497. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52498. };
  52499. /**
  52500. * Helper function to auto-create an ActionEvent from a primitive
  52501. * @param prim defines the target primitive
  52502. * @param pointerPos defines the pointer position
  52503. * @param evt The original (browser) event
  52504. * @param additionalData additional data for the event
  52505. * @returns the new ActionEvent
  52506. */
  52507. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52508. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52509. };
  52510. return ActionEvent;
  52511. }());
  52512. BABYLON.ActionEvent = ActionEvent;
  52513. /**
  52514. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52515. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52516. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52517. */
  52518. var ActionManager = /** @class */ (function () {
  52519. /**
  52520. * Creates a new action manager
  52521. * @param scene defines the hosting scene
  52522. */
  52523. function ActionManager(scene) {
  52524. // Members
  52525. /** Gets the list of actions */
  52526. this.actions = new Array();
  52527. /** Gets the cursor to use when hovering items */
  52528. this.hoverCursor = '';
  52529. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52530. scene.actionManagers.push(this);
  52531. }
  52532. Object.defineProperty(ActionManager, "NothingTrigger", {
  52533. /**
  52534. * Nothing
  52535. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52536. */
  52537. get: function () {
  52538. return ActionManager._NothingTrigger;
  52539. },
  52540. enumerable: true,
  52541. configurable: true
  52542. });
  52543. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52544. /**
  52545. * On pick
  52546. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52547. */
  52548. get: function () {
  52549. return ActionManager._OnPickTrigger;
  52550. },
  52551. enumerable: true,
  52552. configurable: true
  52553. });
  52554. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52555. /**
  52556. * On left pick
  52557. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52558. */
  52559. get: function () {
  52560. return ActionManager._OnLeftPickTrigger;
  52561. },
  52562. enumerable: true,
  52563. configurable: true
  52564. });
  52565. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52566. /**
  52567. * On right pick
  52568. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52569. */
  52570. get: function () {
  52571. return ActionManager._OnRightPickTrigger;
  52572. },
  52573. enumerable: true,
  52574. configurable: true
  52575. });
  52576. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52577. /**
  52578. * On center pick
  52579. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52580. */
  52581. get: function () {
  52582. return ActionManager._OnCenterPickTrigger;
  52583. },
  52584. enumerable: true,
  52585. configurable: true
  52586. });
  52587. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52588. /**
  52589. * On pick down
  52590. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52591. */
  52592. get: function () {
  52593. return ActionManager._OnPickDownTrigger;
  52594. },
  52595. enumerable: true,
  52596. configurable: true
  52597. });
  52598. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52599. /**
  52600. * On double pick
  52601. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52602. */
  52603. get: function () {
  52604. return ActionManager._OnDoublePickTrigger;
  52605. },
  52606. enumerable: true,
  52607. configurable: true
  52608. });
  52609. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52610. /**
  52611. * On pick up
  52612. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52613. */
  52614. get: function () {
  52615. return ActionManager._OnPickUpTrigger;
  52616. },
  52617. enumerable: true,
  52618. configurable: true
  52619. });
  52620. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52621. /**
  52622. * On pick out.
  52623. * This trigger will only be raised if you also declared a OnPickDown
  52624. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52625. */
  52626. get: function () {
  52627. return ActionManager._OnPickOutTrigger;
  52628. },
  52629. enumerable: true,
  52630. configurable: true
  52631. });
  52632. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52633. /**
  52634. * On long press
  52635. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52636. */
  52637. get: function () {
  52638. return ActionManager._OnLongPressTrigger;
  52639. },
  52640. enumerable: true,
  52641. configurable: true
  52642. });
  52643. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52644. /**
  52645. * On pointer over
  52646. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52647. */
  52648. get: function () {
  52649. return ActionManager._OnPointerOverTrigger;
  52650. },
  52651. enumerable: true,
  52652. configurable: true
  52653. });
  52654. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52655. /**
  52656. * On pointer out
  52657. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52658. */
  52659. get: function () {
  52660. return ActionManager._OnPointerOutTrigger;
  52661. },
  52662. enumerable: true,
  52663. configurable: true
  52664. });
  52665. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52666. /**
  52667. * On every frame
  52668. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52669. */
  52670. get: function () {
  52671. return ActionManager._OnEveryFrameTrigger;
  52672. },
  52673. enumerable: true,
  52674. configurable: true
  52675. });
  52676. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52677. /**
  52678. * On intersection enter
  52679. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52680. */
  52681. get: function () {
  52682. return ActionManager._OnIntersectionEnterTrigger;
  52683. },
  52684. enumerable: true,
  52685. configurable: true
  52686. });
  52687. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52688. /**
  52689. * On intersection exit
  52690. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52691. */
  52692. get: function () {
  52693. return ActionManager._OnIntersectionExitTrigger;
  52694. },
  52695. enumerable: true,
  52696. configurable: true
  52697. });
  52698. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52699. /**
  52700. * On key down
  52701. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52702. */
  52703. get: function () {
  52704. return ActionManager._OnKeyDownTrigger;
  52705. },
  52706. enumerable: true,
  52707. configurable: true
  52708. });
  52709. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52710. /**
  52711. * On key up
  52712. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52713. */
  52714. get: function () {
  52715. return ActionManager._OnKeyUpTrigger;
  52716. },
  52717. enumerable: true,
  52718. configurable: true
  52719. });
  52720. // Methods
  52721. /**
  52722. * Releases all associated resources
  52723. */
  52724. ActionManager.prototype.dispose = function () {
  52725. var index = this._scene.actionManagers.indexOf(this);
  52726. for (var i = 0; i < this.actions.length; i++) {
  52727. var action = this.actions[i];
  52728. ActionManager.Triggers[action.trigger]--;
  52729. if (ActionManager.Triggers[action.trigger] === 0) {
  52730. delete ActionManager.Triggers[action.trigger];
  52731. }
  52732. }
  52733. if (index > -1) {
  52734. this._scene.actionManagers.splice(index, 1);
  52735. }
  52736. };
  52737. /**
  52738. * Gets hosting scene
  52739. * @returns the hosting scene
  52740. */
  52741. ActionManager.prototype.getScene = function () {
  52742. return this._scene;
  52743. };
  52744. /**
  52745. * Does this action manager handles actions of any of the given triggers
  52746. * @param triggers defines the triggers to be tested
  52747. * @return a boolean indicating whether one (or more) of the triggers is handled
  52748. */
  52749. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52750. for (var index = 0; index < this.actions.length; index++) {
  52751. var action = this.actions[index];
  52752. if (triggers.indexOf(action.trigger) > -1) {
  52753. return true;
  52754. }
  52755. }
  52756. return false;
  52757. };
  52758. /**
  52759. * Does this action manager handles actions of a given trigger
  52760. * @param trigger defines the trigger to be tested
  52761. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52762. * @return whether the trigger is handled
  52763. */
  52764. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52765. for (var index = 0; index < this.actions.length; index++) {
  52766. var action = this.actions[index];
  52767. if (action.trigger === trigger) {
  52768. if (parameterPredicate) {
  52769. if (parameterPredicate(action.getTriggerParameter())) {
  52770. return true;
  52771. }
  52772. }
  52773. else {
  52774. return true;
  52775. }
  52776. }
  52777. }
  52778. return false;
  52779. };
  52780. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52781. /**
  52782. * Does this action manager has pointer triggers
  52783. */
  52784. get: function () {
  52785. for (var index = 0; index < this.actions.length; index++) {
  52786. var action = this.actions[index];
  52787. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52788. return true;
  52789. }
  52790. }
  52791. return false;
  52792. },
  52793. enumerable: true,
  52794. configurable: true
  52795. });
  52796. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52797. /**
  52798. * Does this action manager has pick triggers
  52799. */
  52800. get: function () {
  52801. for (var index = 0; index < this.actions.length; index++) {
  52802. var action = this.actions[index];
  52803. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52804. return true;
  52805. }
  52806. }
  52807. return false;
  52808. },
  52809. enumerable: true,
  52810. configurable: true
  52811. });
  52812. Object.defineProperty(ActionManager, "HasTriggers", {
  52813. /**
  52814. * Does exist one action manager with at least one trigger
  52815. **/
  52816. get: function () {
  52817. for (var t in ActionManager.Triggers) {
  52818. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52819. return true;
  52820. }
  52821. }
  52822. return false;
  52823. },
  52824. enumerable: true,
  52825. configurable: true
  52826. });
  52827. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52828. /**
  52829. * Does exist one action manager with at least one pick trigger
  52830. **/
  52831. get: function () {
  52832. for (var t in ActionManager.Triggers) {
  52833. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52834. var t_int = parseInt(t);
  52835. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52836. return true;
  52837. }
  52838. }
  52839. }
  52840. return false;
  52841. },
  52842. enumerable: true,
  52843. configurable: true
  52844. });
  52845. /**
  52846. * Does exist one action manager that handles actions of a given trigger
  52847. * @param trigger defines the trigger to be tested
  52848. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52849. **/
  52850. ActionManager.HasSpecificTrigger = function (trigger) {
  52851. for (var t in ActionManager.Triggers) {
  52852. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52853. var t_int = parseInt(t);
  52854. if (t_int === trigger) {
  52855. return true;
  52856. }
  52857. }
  52858. }
  52859. return false;
  52860. };
  52861. /**
  52862. * Registers an action to this action manager
  52863. * @param action defines the action to be registered
  52864. * @return the action amended (prepared) after registration
  52865. */
  52866. ActionManager.prototype.registerAction = function (action) {
  52867. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52868. if (this.getScene().actionManager !== this) {
  52869. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52870. return null;
  52871. }
  52872. }
  52873. this.actions.push(action);
  52874. if (ActionManager.Triggers[action.trigger]) {
  52875. ActionManager.Triggers[action.trigger]++;
  52876. }
  52877. else {
  52878. ActionManager.Triggers[action.trigger] = 1;
  52879. }
  52880. action._actionManager = this;
  52881. action._prepare();
  52882. return action;
  52883. };
  52884. /**
  52885. * Unregisters an action to this action manager
  52886. * @param action defines the action to be unregistered
  52887. * @return a boolean indicating whether the action has been unregistered
  52888. */
  52889. ActionManager.prototype.unregisterAction = function (action) {
  52890. var index = this.actions.indexOf(action);
  52891. if (index !== -1) {
  52892. this.actions.splice(index, 1);
  52893. ActionManager.Triggers[action.trigger] -= 1;
  52894. if (ActionManager.Triggers[action.trigger] === 0) {
  52895. delete ActionManager.Triggers[action.trigger];
  52896. }
  52897. delete action._actionManager;
  52898. return true;
  52899. }
  52900. return false;
  52901. };
  52902. /**
  52903. * Process a specific trigger
  52904. * @param trigger defines the trigger to process
  52905. * @param evt defines the event details to be processed
  52906. */
  52907. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52908. for (var index = 0; index < this.actions.length; index++) {
  52909. var action = this.actions[index];
  52910. if (action.trigger === trigger) {
  52911. if (evt) {
  52912. if (trigger === ActionManager.OnKeyUpTrigger
  52913. || trigger === ActionManager.OnKeyDownTrigger) {
  52914. var parameter = action.getTriggerParameter();
  52915. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52916. if (!parameter.toLowerCase) {
  52917. continue;
  52918. }
  52919. var lowerCase = parameter.toLowerCase();
  52920. if (lowerCase !== evt.sourceEvent.key) {
  52921. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52922. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52923. if (actualkey !== lowerCase) {
  52924. continue;
  52925. }
  52926. }
  52927. }
  52928. }
  52929. }
  52930. action._executeCurrent(evt);
  52931. }
  52932. }
  52933. };
  52934. /** @hidden */
  52935. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52936. var properties = propertyPath.split(".");
  52937. for (var index = 0; index < properties.length - 1; index++) {
  52938. target = target[properties[index]];
  52939. }
  52940. return target;
  52941. };
  52942. /** @hidden */
  52943. ActionManager.prototype._getProperty = function (propertyPath) {
  52944. var properties = propertyPath.split(".");
  52945. return properties[properties.length - 1];
  52946. };
  52947. /**
  52948. * Serialize this manager to a JSON object
  52949. * @param name defines the property name to store this manager
  52950. * @returns a JSON representation of this manager
  52951. */
  52952. ActionManager.prototype.serialize = function (name) {
  52953. var root = {
  52954. children: new Array(),
  52955. name: name,
  52956. type: 3,
  52957. properties: new Array() // Empty for root but required
  52958. };
  52959. for (var i = 0; i < this.actions.length; i++) {
  52960. var triggerObject = {
  52961. type: 0,
  52962. children: new Array(),
  52963. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52964. properties: new Array()
  52965. };
  52966. var triggerOptions = this.actions[i].triggerOptions;
  52967. if (triggerOptions && typeof triggerOptions !== "number") {
  52968. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52969. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52970. }
  52971. else {
  52972. var parameter = {};
  52973. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52974. if (triggerOptions.parameter.mesh) {
  52975. parameter._meshId = triggerOptions.parameter.mesh.id;
  52976. }
  52977. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52978. }
  52979. }
  52980. // Serialize child action, recursively
  52981. this.actions[i].serialize(triggerObject);
  52982. // Add serialized trigger
  52983. root.children.push(triggerObject);
  52984. }
  52985. return root;
  52986. };
  52987. /**
  52988. * Creates a new ActionManager from a JSON data
  52989. * @param parsedActions defines the JSON data to read from
  52990. * @param object defines the hosting mesh
  52991. * @param scene defines the hosting scene
  52992. */
  52993. ActionManager.Parse = function (parsedActions, object, scene) {
  52994. var actionManager = new ActionManager(scene);
  52995. if (object === null)
  52996. scene.actionManager = actionManager;
  52997. else
  52998. object.actionManager = actionManager;
  52999. // instanciate a new object
  53000. var instanciate = function (name, params) {
  53001. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53002. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53003. newInstance.constructor.apply(newInstance, params);
  53004. return newInstance;
  53005. };
  53006. var parseParameter = function (name, value, target, propertyPath) {
  53007. if (propertyPath === null) {
  53008. // String, boolean or float
  53009. var floatValue = parseFloat(value);
  53010. if (value === "true" || value === "false")
  53011. return value === "true";
  53012. else
  53013. return isNaN(floatValue) ? value : floatValue;
  53014. }
  53015. var effectiveTarget = propertyPath.split(".");
  53016. var values = value.split(",");
  53017. // Get effective Target
  53018. for (var i = 0; i < effectiveTarget.length; i++) {
  53019. target = target[effectiveTarget[i]];
  53020. }
  53021. // Return appropriate value with its type
  53022. if (typeof (target) === "boolean")
  53023. return values[0] === "true";
  53024. if (typeof (target) === "string")
  53025. return values[0];
  53026. // Parameters with multiple values such as Vector3 etc.
  53027. var split = new Array();
  53028. for (var i = 0; i < values.length; i++)
  53029. split.push(parseFloat(values[i]));
  53030. if (target instanceof BABYLON.Vector3)
  53031. return BABYLON.Vector3.FromArray(split);
  53032. if (target instanceof BABYLON.Vector4)
  53033. return BABYLON.Vector4.FromArray(split);
  53034. if (target instanceof BABYLON.Color3)
  53035. return BABYLON.Color3.FromArray(split);
  53036. if (target instanceof BABYLON.Color4)
  53037. return BABYLON.Color4.FromArray(split);
  53038. return parseFloat(values[0]);
  53039. };
  53040. // traverse graph per trigger
  53041. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53042. if (combineArray === void 0) { combineArray = null; }
  53043. if (parsedAction.detached)
  53044. return;
  53045. var parameters = new Array();
  53046. var target = null;
  53047. var propertyPath = null;
  53048. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53049. // Parameters
  53050. if (parsedAction.type === 2)
  53051. parameters.push(actionManager);
  53052. else
  53053. parameters.push(trigger);
  53054. if (combine) {
  53055. var actions = new Array();
  53056. for (var j = 0; j < parsedAction.combine.length; j++) {
  53057. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53058. }
  53059. parameters.push(actions);
  53060. }
  53061. else {
  53062. for (var i = 0; i < parsedAction.properties.length; i++) {
  53063. var value = parsedAction.properties[i].value;
  53064. var name = parsedAction.properties[i].name;
  53065. var targetType = parsedAction.properties[i].targetType;
  53066. if (name === "target")
  53067. if (targetType !== null && targetType === "SceneProperties")
  53068. value = target = scene;
  53069. else
  53070. value = target = scene.getNodeByName(value);
  53071. else if (name === "parent")
  53072. value = scene.getNodeByName(value);
  53073. else if (name === "sound")
  53074. value = scene.getSoundByName(value);
  53075. else if (name !== "propertyPath") {
  53076. if (parsedAction.type === 2 && name === "operator")
  53077. value = BABYLON.ValueCondition[value];
  53078. else
  53079. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53080. }
  53081. else {
  53082. propertyPath = value;
  53083. }
  53084. parameters.push(value);
  53085. }
  53086. }
  53087. if (combineArray === null) {
  53088. parameters.push(condition);
  53089. }
  53090. else {
  53091. parameters.push(null);
  53092. }
  53093. // If interpolate value action
  53094. if (parsedAction.name === "InterpolateValueAction") {
  53095. var param = parameters[parameters.length - 2];
  53096. parameters[parameters.length - 1] = param;
  53097. parameters[parameters.length - 2] = condition;
  53098. }
  53099. // Action or condition(s) and not CombineAction
  53100. var newAction = instanciate(parsedAction.name, parameters);
  53101. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53102. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53103. if (action)
  53104. action.then(nothing);
  53105. else
  53106. actionManager.registerAction(nothing);
  53107. action = nothing;
  53108. }
  53109. if (combineArray === null) {
  53110. if (newAction instanceof BABYLON.Condition) {
  53111. condition = newAction;
  53112. newAction = action;
  53113. }
  53114. else {
  53115. condition = null;
  53116. if (action)
  53117. action.then(newAction);
  53118. else
  53119. actionManager.registerAction(newAction);
  53120. }
  53121. }
  53122. else {
  53123. combineArray.push(newAction);
  53124. }
  53125. for (var i = 0; i < parsedAction.children.length; i++)
  53126. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53127. };
  53128. // triggers
  53129. for (var i = 0; i < parsedActions.children.length; i++) {
  53130. var triggerParams;
  53131. var trigger = parsedActions.children[i];
  53132. if (trigger.properties.length > 0) {
  53133. var param = trigger.properties[0].value;
  53134. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53135. if (value._meshId) {
  53136. value.mesh = scene.getMeshByID(value._meshId);
  53137. }
  53138. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53139. }
  53140. else
  53141. triggerParams = ActionManager[trigger.name];
  53142. for (var j = 0; j < trigger.children.length; j++) {
  53143. if (!trigger.detached)
  53144. traverse(trigger.children[j], triggerParams, null, null);
  53145. }
  53146. }
  53147. };
  53148. /**
  53149. * Get a trigger name by index
  53150. * @param trigger defines the trigger index
  53151. * @returns a trigger name
  53152. */
  53153. ActionManager.GetTriggerName = function (trigger) {
  53154. switch (trigger) {
  53155. case 0: return "NothingTrigger";
  53156. case 1: return "OnPickTrigger";
  53157. case 2: return "OnLeftPickTrigger";
  53158. case 3: return "OnRightPickTrigger";
  53159. case 4: return "OnCenterPickTrigger";
  53160. case 5: return "OnPickDownTrigger";
  53161. case 6: return "OnPickUpTrigger";
  53162. case 7: return "OnLongPressTrigger";
  53163. case 8: return "OnPointerOverTrigger";
  53164. case 9: return "OnPointerOutTrigger";
  53165. case 10: return "OnEveryFrameTrigger";
  53166. case 11: return "OnIntersectionEnterTrigger";
  53167. case 12: return "OnIntersectionExitTrigger";
  53168. case 13: return "OnKeyDownTrigger";
  53169. case 14: return "OnKeyUpTrigger";
  53170. case 15: return "OnPickOutTrigger";
  53171. default: return "";
  53172. }
  53173. };
  53174. // Statics
  53175. ActionManager._NothingTrigger = 0;
  53176. ActionManager._OnPickTrigger = 1;
  53177. ActionManager._OnLeftPickTrigger = 2;
  53178. ActionManager._OnRightPickTrigger = 3;
  53179. ActionManager._OnCenterPickTrigger = 4;
  53180. ActionManager._OnPickDownTrigger = 5;
  53181. ActionManager._OnDoublePickTrigger = 6;
  53182. ActionManager._OnPickUpTrigger = 7;
  53183. ActionManager._OnLongPressTrigger = 8;
  53184. ActionManager._OnPointerOverTrigger = 9;
  53185. ActionManager._OnPointerOutTrigger = 10;
  53186. ActionManager._OnEveryFrameTrigger = 11;
  53187. ActionManager._OnIntersectionEnterTrigger = 12;
  53188. ActionManager._OnIntersectionExitTrigger = 13;
  53189. ActionManager._OnKeyDownTrigger = 14;
  53190. ActionManager._OnKeyUpTrigger = 15;
  53191. ActionManager._OnPickOutTrigger = 16;
  53192. /** Gets the list of active triggers */
  53193. ActionManager.Triggers = {};
  53194. return ActionManager;
  53195. }());
  53196. BABYLON.ActionManager = ActionManager;
  53197. })(BABYLON || (BABYLON = {}));
  53198. //# sourceMappingURL=babylon.actionManager.js.map
  53199. var BABYLON;
  53200. (function (BABYLON) {
  53201. var InterpolateValueAction = /** @class */ (function (_super) {
  53202. __extends(InterpolateValueAction, _super);
  53203. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53204. if (duration === void 0) { duration = 1000; }
  53205. var _this = _super.call(this, triggerOptions, condition) || this;
  53206. _this.propertyPath = propertyPath;
  53207. _this.value = value;
  53208. _this.duration = duration;
  53209. _this.stopOtherAnimations = stopOtherAnimations;
  53210. _this.onInterpolationDone = onInterpolationDone;
  53211. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53212. _this._target = _this._effectiveTarget = target;
  53213. return _this;
  53214. }
  53215. InterpolateValueAction.prototype._prepare = function () {
  53216. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53217. this._property = this._getProperty(this.propertyPath);
  53218. };
  53219. InterpolateValueAction.prototype.execute = function () {
  53220. var _this = this;
  53221. var scene = this._actionManager.getScene();
  53222. var keys = [
  53223. {
  53224. frame: 0,
  53225. value: this._effectiveTarget[this._property]
  53226. }, {
  53227. frame: 100,
  53228. value: this.value
  53229. }
  53230. ];
  53231. var dataType;
  53232. if (typeof this.value === "number") {
  53233. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53234. }
  53235. else if (this.value instanceof BABYLON.Color3) {
  53236. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53237. }
  53238. else if (this.value instanceof BABYLON.Vector3) {
  53239. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53240. }
  53241. else if (this.value instanceof BABYLON.Matrix) {
  53242. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53243. }
  53244. else if (this.value instanceof BABYLON.Quaternion) {
  53245. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53246. }
  53247. else {
  53248. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53249. return;
  53250. }
  53251. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53252. animation.setKeys(keys);
  53253. if (this.stopOtherAnimations) {
  53254. scene.stopAnimation(this._effectiveTarget);
  53255. }
  53256. var wrapper = function () {
  53257. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53258. if (_this.onInterpolationDone) {
  53259. _this.onInterpolationDone();
  53260. }
  53261. };
  53262. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53263. };
  53264. InterpolateValueAction.prototype.serialize = function (parent) {
  53265. return _super.prototype._serialize.call(this, {
  53266. name: "InterpolateValueAction",
  53267. properties: [
  53268. BABYLON.Action._GetTargetProperty(this._target),
  53269. { name: "propertyPath", value: this.propertyPath },
  53270. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53271. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53272. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53273. ]
  53274. }, parent);
  53275. };
  53276. return InterpolateValueAction;
  53277. }(BABYLON.Action));
  53278. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53279. })(BABYLON || (BABYLON = {}));
  53280. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53281. var BABYLON;
  53282. (function (BABYLON) {
  53283. var SwitchBooleanAction = /** @class */ (function (_super) {
  53284. __extends(SwitchBooleanAction, _super);
  53285. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53286. var _this = _super.call(this, triggerOptions, condition) || this;
  53287. _this.propertyPath = propertyPath;
  53288. _this._target = _this._effectiveTarget = target;
  53289. return _this;
  53290. }
  53291. SwitchBooleanAction.prototype._prepare = function () {
  53292. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53293. this._property = this._getProperty(this.propertyPath);
  53294. };
  53295. SwitchBooleanAction.prototype.execute = function () {
  53296. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53297. };
  53298. SwitchBooleanAction.prototype.serialize = function (parent) {
  53299. return _super.prototype._serialize.call(this, {
  53300. name: "SwitchBooleanAction",
  53301. properties: [
  53302. BABYLON.Action._GetTargetProperty(this._target),
  53303. { name: "propertyPath", value: this.propertyPath }
  53304. ]
  53305. }, parent);
  53306. };
  53307. return SwitchBooleanAction;
  53308. }(BABYLON.Action));
  53309. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53310. var SetStateAction = /** @class */ (function (_super) {
  53311. __extends(SetStateAction, _super);
  53312. function SetStateAction(triggerOptions, target, value, condition) {
  53313. var _this = _super.call(this, triggerOptions, condition) || this;
  53314. _this.value = value;
  53315. _this._target = target;
  53316. return _this;
  53317. }
  53318. SetStateAction.prototype.execute = function () {
  53319. this._target.state = this.value;
  53320. };
  53321. SetStateAction.prototype.serialize = function (parent) {
  53322. return _super.prototype._serialize.call(this, {
  53323. name: "SetStateAction",
  53324. properties: [
  53325. BABYLON.Action._GetTargetProperty(this._target),
  53326. { name: "value", value: this.value }
  53327. ]
  53328. }, parent);
  53329. };
  53330. return SetStateAction;
  53331. }(BABYLON.Action));
  53332. BABYLON.SetStateAction = SetStateAction;
  53333. var SetValueAction = /** @class */ (function (_super) {
  53334. __extends(SetValueAction, _super);
  53335. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53336. var _this = _super.call(this, triggerOptions, condition) || this;
  53337. _this.propertyPath = propertyPath;
  53338. _this.value = value;
  53339. _this._target = _this._effectiveTarget = target;
  53340. return _this;
  53341. }
  53342. SetValueAction.prototype._prepare = function () {
  53343. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53344. this._property = this._getProperty(this.propertyPath);
  53345. };
  53346. SetValueAction.prototype.execute = function () {
  53347. this._effectiveTarget[this._property] = this.value;
  53348. if (this._target.markAsDirty) {
  53349. this._target.markAsDirty(this._property);
  53350. }
  53351. };
  53352. SetValueAction.prototype.serialize = function (parent) {
  53353. return _super.prototype._serialize.call(this, {
  53354. name: "SetValueAction",
  53355. properties: [
  53356. BABYLON.Action._GetTargetProperty(this._target),
  53357. { name: "propertyPath", value: this.propertyPath },
  53358. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53359. ]
  53360. }, parent);
  53361. };
  53362. return SetValueAction;
  53363. }(BABYLON.Action));
  53364. BABYLON.SetValueAction = SetValueAction;
  53365. var IncrementValueAction = /** @class */ (function (_super) {
  53366. __extends(IncrementValueAction, _super);
  53367. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53368. var _this = _super.call(this, triggerOptions, condition) || this;
  53369. _this.propertyPath = propertyPath;
  53370. _this.value = value;
  53371. _this._target = _this._effectiveTarget = target;
  53372. return _this;
  53373. }
  53374. IncrementValueAction.prototype._prepare = function () {
  53375. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53376. this._property = this._getProperty(this.propertyPath);
  53377. if (typeof this._effectiveTarget[this._property] !== "number") {
  53378. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53379. }
  53380. };
  53381. IncrementValueAction.prototype.execute = function () {
  53382. this._effectiveTarget[this._property] += this.value;
  53383. if (this._target.markAsDirty) {
  53384. this._target.markAsDirty(this._property);
  53385. }
  53386. };
  53387. IncrementValueAction.prototype.serialize = function (parent) {
  53388. return _super.prototype._serialize.call(this, {
  53389. name: "IncrementValueAction",
  53390. properties: [
  53391. BABYLON.Action._GetTargetProperty(this._target),
  53392. { name: "propertyPath", value: this.propertyPath },
  53393. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53394. ]
  53395. }, parent);
  53396. };
  53397. return IncrementValueAction;
  53398. }(BABYLON.Action));
  53399. BABYLON.IncrementValueAction = IncrementValueAction;
  53400. var PlayAnimationAction = /** @class */ (function (_super) {
  53401. __extends(PlayAnimationAction, _super);
  53402. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53403. var _this = _super.call(this, triggerOptions, condition) || this;
  53404. _this.from = from;
  53405. _this.to = to;
  53406. _this.loop = loop;
  53407. _this._target = target;
  53408. return _this;
  53409. }
  53410. PlayAnimationAction.prototype._prepare = function () {
  53411. };
  53412. PlayAnimationAction.prototype.execute = function () {
  53413. var scene = this._actionManager.getScene();
  53414. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53415. };
  53416. PlayAnimationAction.prototype.serialize = function (parent) {
  53417. return _super.prototype._serialize.call(this, {
  53418. name: "PlayAnimationAction",
  53419. properties: [
  53420. BABYLON.Action._GetTargetProperty(this._target),
  53421. { name: "from", value: String(this.from) },
  53422. { name: "to", value: String(this.to) },
  53423. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53424. ]
  53425. }, parent);
  53426. };
  53427. return PlayAnimationAction;
  53428. }(BABYLON.Action));
  53429. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53430. var StopAnimationAction = /** @class */ (function (_super) {
  53431. __extends(StopAnimationAction, _super);
  53432. function StopAnimationAction(triggerOptions, target, condition) {
  53433. var _this = _super.call(this, triggerOptions, condition) || this;
  53434. _this._target = target;
  53435. return _this;
  53436. }
  53437. StopAnimationAction.prototype._prepare = function () {
  53438. };
  53439. StopAnimationAction.prototype.execute = function () {
  53440. var scene = this._actionManager.getScene();
  53441. scene.stopAnimation(this._target);
  53442. };
  53443. StopAnimationAction.prototype.serialize = function (parent) {
  53444. return _super.prototype._serialize.call(this, {
  53445. name: "StopAnimationAction",
  53446. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53447. }, parent);
  53448. };
  53449. return StopAnimationAction;
  53450. }(BABYLON.Action));
  53451. BABYLON.StopAnimationAction = StopAnimationAction;
  53452. var DoNothingAction = /** @class */ (function (_super) {
  53453. __extends(DoNothingAction, _super);
  53454. function DoNothingAction(triggerOptions, condition) {
  53455. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53456. return _super.call(this, triggerOptions, condition) || this;
  53457. }
  53458. DoNothingAction.prototype.execute = function () {
  53459. };
  53460. DoNothingAction.prototype.serialize = function (parent) {
  53461. return _super.prototype._serialize.call(this, {
  53462. name: "DoNothingAction",
  53463. properties: []
  53464. }, parent);
  53465. };
  53466. return DoNothingAction;
  53467. }(BABYLON.Action));
  53468. BABYLON.DoNothingAction = DoNothingAction;
  53469. var CombineAction = /** @class */ (function (_super) {
  53470. __extends(CombineAction, _super);
  53471. function CombineAction(triggerOptions, children, condition) {
  53472. var _this = _super.call(this, triggerOptions, condition) || this;
  53473. _this.children = children;
  53474. return _this;
  53475. }
  53476. CombineAction.prototype._prepare = function () {
  53477. for (var index = 0; index < this.children.length; index++) {
  53478. this.children[index]._actionManager = this._actionManager;
  53479. this.children[index]._prepare();
  53480. }
  53481. };
  53482. CombineAction.prototype.execute = function (evt) {
  53483. for (var index = 0; index < this.children.length; index++) {
  53484. this.children[index].execute(evt);
  53485. }
  53486. };
  53487. CombineAction.prototype.serialize = function (parent) {
  53488. var serializationObject = _super.prototype._serialize.call(this, {
  53489. name: "CombineAction",
  53490. properties: [],
  53491. combine: []
  53492. }, parent);
  53493. for (var i = 0; i < this.children.length; i++) {
  53494. serializationObject.combine.push(this.children[i].serialize(null));
  53495. }
  53496. return serializationObject;
  53497. };
  53498. return CombineAction;
  53499. }(BABYLON.Action));
  53500. BABYLON.CombineAction = CombineAction;
  53501. var ExecuteCodeAction = /** @class */ (function (_super) {
  53502. __extends(ExecuteCodeAction, _super);
  53503. function ExecuteCodeAction(triggerOptions, func, condition) {
  53504. var _this = _super.call(this, triggerOptions, condition) || this;
  53505. _this.func = func;
  53506. return _this;
  53507. }
  53508. ExecuteCodeAction.prototype.execute = function (evt) {
  53509. this.func(evt);
  53510. };
  53511. return ExecuteCodeAction;
  53512. }(BABYLON.Action));
  53513. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53514. var SetParentAction = /** @class */ (function (_super) {
  53515. __extends(SetParentAction, _super);
  53516. function SetParentAction(triggerOptions, target, parent, condition) {
  53517. var _this = _super.call(this, triggerOptions, condition) || this;
  53518. _this._target = target;
  53519. _this._parent = parent;
  53520. return _this;
  53521. }
  53522. SetParentAction.prototype._prepare = function () {
  53523. };
  53524. SetParentAction.prototype.execute = function () {
  53525. if (this._target.parent === this._parent) {
  53526. return;
  53527. }
  53528. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53529. invertParentWorldMatrix.invert();
  53530. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53531. this._target.parent = this._parent;
  53532. };
  53533. SetParentAction.prototype.serialize = function (parent) {
  53534. return _super.prototype._serialize.call(this, {
  53535. name: "SetParentAction",
  53536. properties: [
  53537. BABYLON.Action._GetTargetProperty(this._target),
  53538. BABYLON.Action._GetTargetProperty(this._parent),
  53539. ]
  53540. }, parent);
  53541. };
  53542. return SetParentAction;
  53543. }(BABYLON.Action));
  53544. BABYLON.SetParentAction = SetParentAction;
  53545. var PlaySoundAction = /** @class */ (function (_super) {
  53546. __extends(PlaySoundAction, _super);
  53547. function PlaySoundAction(triggerOptions, sound, condition) {
  53548. var _this = _super.call(this, triggerOptions, condition) || this;
  53549. _this._sound = sound;
  53550. return _this;
  53551. }
  53552. PlaySoundAction.prototype._prepare = function () {
  53553. };
  53554. PlaySoundAction.prototype.execute = function () {
  53555. if (this._sound !== undefined)
  53556. this._sound.play();
  53557. };
  53558. PlaySoundAction.prototype.serialize = function (parent) {
  53559. return _super.prototype._serialize.call(this, {
  53560. name: "PlaySoundAction",
  53561. properties: [{ name: "sound", value: this._sound.name }]
  53562. }, parent);
  53563. };
  53564. return PlaySoundAction;
  53565. }(BABYLON.Action));
  53566. BABYLON.PlaySoundAction = PlaySoundAction;
  53567. var StopSoundAction = /** @class */ (function (_super) {
  53568. __extends(StopSoundAction, _super);
  53569. function StopSoundAction(triggerOptions, sound, condition) {
  53570. var _this = _super.call(this, triggerOptions, condition) || this;
  53571. _this._sound = sound;
  53572. return _this;
  53573. }
  53574. StopSoundAction.prototype._prepare = function () {
  53575. };
  53576. StopSoundAction.prototype.execute = function () {
  53577. if (this._sound !== undefined)
  53578. this._sound.stop();
  53579. };
  53580. StopSoundAction.prototype.serialize = function (parent) {
  53581. return _super.prototype._serialize.call(this, {
  53582. name: "StopSoundAction",
  53583. properties: [{ name: "sound", value: this._sound.name }]
  53584. }, parent);
  53585. };
  53586. return StopSoundAction;
  53587. }(BABYLON.Action));
  53588. BABYLON.StopSoundAction = StopSoundAction;
  53589. })(BABYLON || (BABYLON = {}));
  53590. //# sourceMappingURL=babylon.directActions.js.map
  53591. var BABYLON;
  53592. (function (BABYLON) {
  53593. var SpriteManager = /** @class */ (function () {
  53594. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53595. if (epsilon === void 0) { epsilon = 0.01; }
  53596. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53597. this.name = name;
  53598. this.sprites = new Array();
  53599. this.renderingGroupId = 0;
  53600. this.layerMask = 0x0FFFFFFF;
  53601. this.fogEnabled = true;
  53602. this.isPickable = false;
  53603. /**
  53604. * An event triggered when the manager is disposed.
  53605. */
  53606. this.onDisposeObservable = new BABYLON.Observable();
  53607. this._vertexBuffers = {};
  53608. this._capacity = capacity;
  53609. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53610. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53611. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53612. if (cellSize.width && cellSize.height) {
  53613. this.cellWidth = cellSize.width;
  53614. this.cellHeight = cellSize.height;
  53615. }
  53616. else if (cellSize !== undefined) {
  53617. this.cellWidth = cellSize;
  53618. this.cellHeight = cellSize;
  53619. }
  53620. else {
  53621. return;
  53622. }
  53623. this._epsilon = epsilon;
  53624. this._scene = scene;
  53625. this._scene.spriteManagers.push(this);
  53626. var indices = [];
  53627. var index = 0;
  53628. for (var count = 0; count < capacity; count++) {
  53629. indices.push(index);
  53630. indices.push(index + 1);
  53631. indices.push(index + 2);
  53632. indices.push(index);
  53633. indices.push(index + 2);
  53634. indices.push(index + 3);
  53635. index += 4;
  53636. }
  53637. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53638. // VBO
  53639. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53640. this._vertexData = new Float32Array(capacity * 16 * 4);
  53641. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53642. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53643. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53644. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53645. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53646. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53647. this._vertexBuffers["options"] = options;
  53648. this._vertexBuffers["cellInfo"] = cellInfo;
  53649. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53650. // Effects
  53651. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53652. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53653. }
  53654. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53655. set: function (callback) {
  53656. if (this._onDisposeObserver) {
  53657. this.onDisposeObservable.remove(this._onDisposeObserver);
  53658. }
  53659. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53660. },
  53661. enumerable: true,
  53662. configurable: true
  53663. });
  53664. Object.defineProperty(SpriteManager.prototype, "texture", {
  53665. get: function () {
  53666. return this._spriteTexture;
  53667. },
  53668. set: function (value) {
  53669. this._spriteTexture = value;
  53670. },
  53671. enumerable: true,
  53672. configurable: true
  53673. });
  53674. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53675. var arrayOffset = index * 16;
  53676. if (offsetX === 0)
  53677. offsetX = this._epsilon;
  53678. else if (offsetX === 1)
  53679. offsetX = 1 - this._epsilon;
  53680. if (offsetY === 0)
  53681. offsetY = this._epsilon;
  53682. else if (offsetY === 1)
  53683. offsetY = 1 - this._epsilon;
  53684. this._vertexData[arrayOffset] = sprite.position.x;
  53685. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53686. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53687. this._vertexData[arrayOffset + 3] = sprite.angle;
  53688. this._vertexData[arrayOffset + 4] = sprite.width;
  53689. this._vertexData[arrayOffset + 5] = sprite.height;
  53690. this._vertexData[arrayOffset + 6] = offsetX;
  53691. this._vertexData[arrayOffset + 7] = offsetY;
  53692. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53693. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53694. var offset = (sprite.cellIndex / rowSize) >> 0;
  53695. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53696. this._vertexData[arrayOffset + 11] = offset;
  53697. // Color
  53698. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53699. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53700. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53701. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53702. };
  53703. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53704. var count = Math.min(this._capacity, this.sprites.length);
  53705. var min = BABYLON.Vector3.Zero();
  53706. var max = BABYLON.Vector3.Zero();
  53707. var distance = Number.MAX_VALUE;
  53708. var currentSprite = null;
  53709. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53710. var cameraView = camera.getViewMatrix();
  53711. for (var index = 0; index < count; index++) {
  53712. var sprite = this.sprites[index];
  53713. if (!sprite) {
  53714. continue;
  53715. }
  53716. if (predicate) {
  53717. if (!predicate(sprite)) {
  53718. continue;
  53719. }
  53720. }
  53721. else if (!sprite.isPickable) {
  53722. continue;
  53723. }
  53724. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53725. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53726. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53727. if (ray.intersectsBoxMinMax(min, max)) {
  53728. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53729. if (distance > currentDistance) {
  53730. distance = currentDistance;
  53731. currentSprite = sprite;
  53732. if (fastCheck) {
  53733. break;
  53734. }
  53735. }
  53736. }
  53737. }
  53738. if (currentSprite) {
  53739. var result = new BABYLON.PickingInfo();
  53740. result.hit = true;
  53741. result.pickedSprite = currentSprite;
  53742. result.distance = distance;
  53743. return result;
  53744. }
  53745. return null;
  53746. };
  53747. SpriteManager.prototype.render = function () {
  53748. // Check
  53749. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53750. return;
  53751. var engine = this._scene.getEngine();
  53752. var baseSize = this._spriteTexture.getBaseSize();
  53753. // Sprites
  53754. var deltaTime = engine.getDeltaTime();
  53755. var max = Math.min(this._capacity, this.sprites.length);
  53756. var rowSize = baseSize.width / this.cellWidth;
  53757. var offset = 0;
  53758. for (var index = 0; index < max; index++) {
  53759. var sprite = this.sprites[index];
  53760. if (!sprite || !sprite.isVisible) {
  53761. continue;
  53762. }
  53763. sprite._animate(deltaTime);
  53764. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53765. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53766. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53767. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53768. }
  53769. this._buffer.update(this._vertexData);
  53770. // Render
  53771. var effect = this._effectBase;
  53772. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53773. effect = this._effectFog;
  53774. }
  53775. engine.enableEffect(effect);
  53776. var viewMatrix = this._scene.getViewMatrix();
  53777. effect.setTexture("diffuseSampler", this._spriteTexture);
  53778. effect.setMatrix("view", viewMatrix);
  53779. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53780. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53781. // Fog
  53782. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53783. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53784. effect.setColor3("vFogColor", this._scene.fogColor);
  53785. }
  53786. // VBOs
  53787. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53788. // Draw order
  53789. engine.setDepthFunctionToLessOrEqual();
  53790. effect.setBool("alphaTest", true);
  53791. engine.setColorWrite(false);
  53792. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53793. engine.setColorWrite(true);
  53794. effect.setBool("alphaTest", false);
  53795. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53796. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53797. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53798. };
  53799. SpriteManager.prototype.dispose = function () {
  53800. if (this._buffer) {
  53801. this._buffer.dispose();
  53802. this._buffer = null;
  53803. }
  53804. if (this._indexBuffer) {
  53805. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53806. this._indexBuffer = null;
  53807. }
  53808. if (this._spriteTexture) {
  53809. this._spriteTexture.dispose();
  53810. this._spriteTexture = null;
  53811. }
  53812. // Remove from scene
  53813. var index = this._scene.spriteManagers.indexOf(this);
  53814. this._scene.spriteManagers.splice(index, 1);
  53815. // Callback
  53816. this.onDisposeObservable.notifyObservers(this);
  53817. this.onDisposeObservable.clear();
  53818. };
  53819. return SpriteManager;
  53820. }());
  53821. BABYLON.SpriteManager = SpriteManager;
  53822. })(BABYLON || (BABYLON = {}));
  53823. //# sourceMappingURL=babylon.spriteManager.js.map
  53824. var BABYLON;
  53825. (function (BABYLON) {
  53826. var Sprite = /** @class */ (function () {
  53827. function Sprite(name, manager) {
  53828. this.name = name;
  53829. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53830. this.width = 1.0;
  53831. this.height = 1.0;
  53832. this.angle = 0;
  53833. this.cellIndex = 0;
  53834. this.invertU = 0;
  53835. this.invertV = 0;
  53836. this.animations = new Array();
  53837. this.isPickable = false;
  53838. this._animationStarted = false;
  53839. this._loopAnimation = false;
  53840. this._fromIndex = 0;
  53841. this._toIndex = 0;
  53842. this._delay = 0;
  53843. this._direction = 1;
  53844. this._time = 0;
  53845. /**
  53846. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53847. */
  53848. this.isVisible = true;
  53849. this._manager = manager;
  53850. this._manager.sprites.push(this);
  53851. this.position = BABYLON.Vector3.Zero();
  53852. }
  53853. Object.defineProperty(Sprite.prototype, "size", {
  53854. get: function () {
  53855. return this.width;
  53856. },
  53857. set: function (value) {
  53858. this.width = value;
  53859. this.height = value;
  53860. },
  53861. enumerable: true,
  53862. configurable: true
  53863. });
  53864. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53865. this._fromIndex = from;
  53866. this._toIndex = to;
  53867. this._loopAnimation = loop;
  53868. this._delay = delay;
  53869. this._animationStarted = true;
  53870. this._direction = from < to ? 1 : -1;
  53871. this.cellIndex = from;
  53872. this._time = 0;
  53873. this._onAnimationEnd = onAnimationEnd;
  53874. };
  53875. Sprite.prototype.stopAnimation = function () {
  53876. this._animationStarted = false;
  53877. };
  53878. Sprite.prototype._animate = function (deltaTime) {
  53879. if (!this._animationStarted)
  53880. return;
  53881. this._time += deltaTime;
  53882. if (this._time > this._delay) {
  53883. this._time = this._time % this._delay;
  53884. this.cellIndex += this._direction;
  53885. if (this.cellIndex > this._toIndex) {
  53886. if (this._loopAnimation) {
  53887. this.cellIndex = this._fromIndex;
  53888. }
  53889. else {
  53890. this.cellIndex = this._toIndex;
  53891. this._animationStarted = false;
  53892. if (this._onAnimationEnd) {
  53893. this._onAnimationEnd();
  53894. }
  53895. if (this.disposeWhenFinishedAnimating) {
  53896. this.dispose();
  53897. }
  53898. }
  53899. }
  53900. }
  53901. };
  53902. Sprite.prototype.dispose = function () {
  53903. for (var i = 0; i < this._manager.sprites.length; i++) {
  53904. if (this._manager.sprites[i] == this) {
  53905. this._manager.sprites.splice(i, 1);
  53906. }
  53907. }
  53908. };
  53909. return Sprite;
  53910. }());
  53911. BABYLON.Sprite = Sprite;
  53912. })(BABYLON || (BABYLON = {}));
  53913. //# sourceMappingURL=babylon.sprite.js.map
  53914. var BABYLON;
  53915. (function (BABYLON) {
  53916. var IntersectionInfo = /** @class */ (function () {
  53917. function IntersectionInfo(bu, bv, distance) {
  53918. this.bu = bu;
  53919. this.bv = bv;
  53920. this.distance = distance;
  53921. this.faceId = 0;
  53922. this.subMeshId = 0;
  53923. }
  53924. return IntersectionInfo;
  53925. }());
  53926. BABYLON.IntersectionInfo = IntersectionInfo;
  53927. /**
  53928. * Information about the result of picking within a scene
  53929. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53930. */
  53931. var PickingInfo = /** @class */ (function () {
  53932. function PickingInfo() {
  53933. /**
  53934. * If the pick collided with an object
  53935. */
  53936. this.hit = false;
  53937. /**
  53938. * Distance away where the pick collided
  53939. */
  53940. this.distance = 0;
  53941. /**
  53942. * The location of pick collision
  53943. */
  53944. this.pickedPoint = null;
  53945. /**
  53946. * The mesh corrisponding the the pick collision
  53947. */
  53948. this.pickedMesh = null;
  53949. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53950. this.bu = 0;
  53951. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53952. this.bv = 0;
  53953. /** The id of the face on the mesh that was picked */
  53954. this.faceId = -1;
  53955. /** Id of the the submesh that was picked */
  53956. this.subMeshId = 0;
  53957. /** If a sprite was picked, this will be the sprite the pick collided with */
  53958. this.pickedSprite = null;
  53959. /**
  53960. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53961. */
  53962. this.originMesh = null;
  53963. /**
  53964. * The ray that was used to perform the picking.
  53965. */
  53966. this.ray = null;
  53967. }
  53968. /**
  53969. * Gets the normal corrispodning to the face the pick collided with
  53970. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53971. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53972. * @returns The normal corrispodning to the face the pick collided with
  53973. */
  53974. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53975. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53976. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53977. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53978. return null;
  53979. }
  53980. var indices = this.pickedMesh.getIndices();
  53981. if (!indices) {
  53982. return null;
  53983. }
  53984. var result;
  53985. if (useVerticesNormals) {
  53986. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53987. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53988. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53989. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53990. normal0 = normal0.scale(this.bu);
  53991. normal1 = normal1.scale(this.bv);
  53992. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53993. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53994. }
  53995. else {
  53996. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53997. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53998. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53999. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54000. var p1p2 = vertex1.subtract(vertex2);
  54001. var p3p2 = vertex3.subtract(vertex2);
  54002. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54003. }
  54004. if (useWorldCoordinates) {
  54005. var wm = this.pickedMesh.getWorldMatrix();
  54006. if (this.pickedMesh.nonUniformScaling) {
  54007. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54008. wm = BABYLON.Tmp.Matrix[0];
  54009. wm.setTranslationFromFloats(0, 0, 0);
  54010. wm.invert();
  54011. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54012. wm = BABYLON.Tmp.Matrix[1];
  54013. }
  54014. result = BABYLON.Vector3.TransformNormal(result, wm);
  54015. }
  54016. result.normalize();
  54017. return result;
  54018. };
  54019. /**
  54020. * Gets the texture coordinates of where the pick occured
  54021. * @returns the vector containing the coordnates of the texture
  54022. */
  54023. PickingInfo.prototype.getTextureCoordinates = function () {
  54024. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54025. return null;
  54026. }
  54027. var indices = this.pickedMesh.getIndices();
  54028. if (!indices) {
  54029. return null;
  54030. }
  54031. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54032. if (!uvs) {
  54033. return null;
  54034. }
  54035. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54036. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54037. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54038. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54039. uv1 = uv1.scale(this.bu);
  54040. uv2 = uv2.scale(this.bv);
  54041. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54042. };
  54043. return PickingInfo;
  54044. }());
  54045. BABYLON.PickingInfo = PickingInfo;
  54046. })(BABYLON || (BABYLON = {}));
  54047. //# sourceMappingURL=babylon.pickingInfo.js.map
  54048. var BABYLON;
  54049. (function (BABYLON) {
  54050. var Ray = /** @class */ (function () {
  54051. function Ray(origin, direction, length) {
  54052. if (length === void 0) { length = Number.MAX_VALUE; }
  54053. this.origin = origin;
  54054. this.direction = direction;
  54055. this.length = length;
  54056. }
  54057. // Methods
  54058. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54059. var d = 0.0;
  54060. var maxValue = Number.MAX_VALUE;
  54061. var inv;
  54062. var min;
  54063. var max;
  54064. var temp;
  54065. if (Math.abs(this.direction.x) < 0.0000001) {
  54066. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54067. return false;
  54068. }
  54069. }
  54070. else {
  54071. inv = 1.0 / this.direction.x;
  54072. min = (minimum.x - this.origin.x) * inv;
  54073. max = (maximum.x - this.origin.x) * inv;
  54074. if (max === -Infinity) {
  54075. max = Infinity;
  54076. }
  54077. if (min > max) {
  54078. temp = min;
  54079. min = max;
  54080. max = temp;
  54081. }
  54082. d = Math.max(min, d);
  54083. maxValue = Math.min(max, maxValue);
  54084. if (d > maxValue) {
  54085. return false;
  54086. }
  54087. }
  54088. if (Math.abs(this.direction.y) < 0.0000001) {
  54089. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54090. return false;
  54091. }
  54092. }
  54093. else {
  54094. inv = 1.0 / this.direction.y;
  54095. min = (minimum.y - this.origin.y) * inv;
  54096. max = (maximum.y - this.origin.y) * inv;
  54097. if (max === -Infinity) {
  54098. max = Infinity;
  54099. }
  54100. if (min > max) {
  54101. temp = min;
  54102. min = max;
  54103. max = temp;
  54104. }
  54105. d = Math.max(min, d);
  54106. maxValue = Math.min(max, maxValue);
  54107. if (d > maxValue) {
  54108. return false;
  54109. }
  54110. }
  54111. if (Math.abs(this.direction.z) < 0.0000001) {
  54112. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54113. return false;
  54114. }
  54115. }
  54116. else {
  54117. inv = 1.0 / this.direction.z;
  54118. min = (minimum.z - this.origin.z) * inv;
  54119. max = (maximum.z - this.origin.z) * inv;
  54120. if (max === -Infinity) {
  54121. max = Infinity;
  54122. }
  54123. if (min > max) {
  54124. temp = min;
  54125. min = max;
  54126. max = temp;
  54127. }
  54128. d = Math.max(min, d);
  54129. maxValue = Math.min(max, maxValue);
  54130. if (d > maxValue) {
  54131. return false;
  54132. }
  54133. }
  54134. return true;
  54135. };
  54136. Ray.prototype.intersectsBox = function (box) {
  54137. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54138. };
  54139. Ray.prototype.intersectsSphere = function (sphere) {
  54140. var x = sphere.center.x - this.origin.x;
  54141. var y = sphere.center.y - this.origin.y;
  54142. var z = sphere.center.z - this.origin.z;
  54143. var pyth = (x * x) + (y * y) + (z * z);
  54144. var rr = sphere.radius * sphere.radius;
  54145. if (pyth <= rr) {
  54146. return true;
  54147. }
  54148. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54149. if (dot < 0.0) {
  54150. return false;
  54151. }
  54152. var temp = pyth - (dot * dot);
  54153. return temp <= rr;
  54154. };
  54155. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54156. if (!this._edge1) {
  54157. this._edge1 = BABYLON.Vector3.Zero();
  54158. this._edge2 = BABYLON.Vector3.Zero();
  54159. this._pvec = BABYLON.Vector3.Zero();
  54160. this._tvec = BABYLON.Vector3.Zero();
  54161. this._qvec = BABYLON.Vector3.Zero();
  54162. }
  54163. vertex1.subtractToRef(vertex0, this._edge1);
  54164. vertex2.subtractToRef(vertex0, this._edge2);
  54165. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54166. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54167. if (det === 0) {
  54168. return null;
  54169. }
  54170. var invdet = 1 / det;
  54171. this.origin.subtractToRef(vertex0, this._tvec);
  54172. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54173. if (bu < 0 || bu > 1.0) {
  54174. return null;
  54175. }
  54176. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54177. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54178. if (bv < 0 || bu + bv > 1.0) {
  54179. return null;
  54180. }
  54181. //check if the distance is longer than the predefined length.
  54182. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54183. if (distance > this.length) {
  54184. return null;
  54185. }
  54186. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54187. };
  54188. Ray.prototype.intersectsPlane = function (plane) {
  54189. var distance;
  54190. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54191. if (Math.abs(result1) < 9.99999997475243E-07) {
  54192. return null;
  54193. }
  54194. else {
  54195. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54196. distance = (-plane.d - result2) / result1;
  54197. if (distance < 0.0) {
  54198. if (distance < -9.99999997475243E-07) {
  54199. return null;
  54200. }
  54201. else {
  54202. return 0;
  54203. }
  54204. }
  54205. return distance;
  54206. }
  54207. };
  54208. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54209. var tm = BABYLON.Tmp.Matrix[0];
  54210. mesh.getWorldMatrix().invertToRef(tm);
  54211. if (this._tmpRay) {
  54212. Ray.TransformToRef(this, tm, this._tmpRay);
  54213. }
  54214. else {
  54215. this._tmpRay = Ray.Transform(this, tm);
  54216. }
  54217. return mesh.intersects(this._tmpRay, fastCheck);
  54218. };
  54219. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54220. if (results) {
  54221. results.length = 0;
  54222. }
  54223. else {
  54224. results = [];
  54225. }
  54226. for (var i = 0; i < meshes.length; i++) {
  54227. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54228. if (pickInfo.hit) {
  54229. results.push(pickInfo);
  54230. }
  54231. }
  54232. results.sort(this._comparePickingInfo);
  54233. return results;
  54234. };
  54235. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54236. if (pickingInfoA.distance < pickingInfoB.distance) {
  54237. return -1;
  54238. }
  54239. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54240. return 1;
  54241. }
  54242. else {
  54243. return 0;
  54244. }
  54245. };
  54246. /**
  54247. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54248. * @param sega the first point of the segment to test the intersection against
  54249. * @param segb the second point of the segment to test the intersection against
  54250. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54251. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54252. */
  54253. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54254. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54255. var u = segb.subtract(sega);
  54256. var v = rsegb.subtract(this.origin);
  54257. var w = sega.subtract(this.origin);
  54258. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54259. var b = BABYLON.Vector3.Dot(u, v);
  54260. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54261. var d = BABYLON.Vector3.Dot(u, w);
  54262. var e = BABYLON.Vector3.Dot(v, w);
  54263. var D = a * c - b * b; // always >= 0
  54264. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54265. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54266. // compute the line parameters of the two closest points
  54267. if (D < Ray.smallnum) { // the lines are almost parallel
  54268. sN = 0.0; // force using point P0 on segment S1
  54269. sD = 1.0; // to prevent possible division by 0.0 later
  54270. tN = e;
  54271. tD = c;
  54272. }
  54273. else { // get the closest points on the infinite lines
  54274. sN = (b * e - c * d);
  54275. tN = (a * e - b * d);
  54276. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54277. sN = 0.0;
  54278. tN = e;
  54279. tD = c;
  54280. }
  54281. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54282. sN = sD;
  54283. tN = e + b;
  54284. tD = c;
  54285. }
  54286. }
  54287. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54288. tN = 0.0;
  54289. // recompute sc for this edge
  54290. if (-d < 0.0) {
  54291. sN = 0.0;
  54292. }
  54293. else if (-d > a)
  54294. sN = sD;
  54295. else {
  54296. sN = -d;
  54297. sD = a;
  54298. }
  54299. }
  54300. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54301. tN = tD;
  54302. // recompute sc for this edge
  54303. if ((-d + b) < 0.0) {
  54304. sN = 0;
  54305. }
  54306. else if ((-d + b) > a) {
  54307. sN = sD;
  54308. }
  54309. else {
  54310. sN = (-d + b);
  54311. sD = a;
  54312. }
  54313. }
  54314. // finally do the division to get sc and tc
  54315. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54316. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54317. // get the difference of the two closest points
  54318. var qtc = v.multiplyByFloats(tc, tc, tc);
  54319. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54320. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54321. if (isIntersected) {
  54322. return qtc.length();
  54323. }
  54324. return -1;
  54325. };
  54326. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54327. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54328. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54329. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54330. this.direction.normalize();
  54331. return this;
  54332. };
  54333. // Statics
  54334. Ray.Zero = function () {
  54335. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54336. };
  54337. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54338. var result = Ray.Zero();
  54339. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54340. };
  54341. /**
  54342. * 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
  54343. * transformed to the given world matrix.
  54344. * @param origin The origin point
  54345. * @param end The end point
  54346. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54347. */
  54348. Ray.CreateNewFromTo = function (origin, end, world) {
  54349. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54350. var direction = end.subtract(origin);
  54351. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54352. direction.normalize();
  54353. return Ray.Transform(new Ray(origin, direction, length), world);
  54354. };
  54355. Ray.Transform = function (ray, matrix) {
  54356. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54357. Ray.TransformToRef(ray, matrix, result);
  54358. return result;
  54359. };
  54360. Ray.TransformToRef = function (ray, matrix, result) {
  54361. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54362. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54363. result.length = ray.length;
  54364. var dir = result.direction;
  54365. var len = dir.length();
  54366. if (!(len === 0 || len === 1)) {
  54367. var num = 1.0 / len;
  54368. dir.x *= num;
  54369. dir.y *= num;
  54370. dir.z *= num;
  54371. result.length *= len;
  54372. }
  54373. };
  54374. Ray.smallnum = 0.00000001;
  54375. Ray.rayl = 10e8;
  54376. return Ray;
  54377. }());
  54378. BABYLON.Ray = Ray;
  54379. })(BABYLON || (BABYLON = {}));
  54380. //# sourceMappingURL=babylon.ray.js.map
  54381. var BABYLON;
  54382. (function (BABYLON) {
  54383. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54384. if (boxMin.x > sphereCenter.x + sphereRadius)
  54385. return false;
  54386. if (sphereCenter.x - sphereRadius > boxMax.x)
  54387. return false;
  54388. if (boxMin.y > sphereCenter.y + sphereRadius)
  54389. return false;
  54390. if (sphereCenter.y - sphereRadius > boxMax.y)
  54391. return false;
  54392. if (boxMin.z > sphereCenter.z + sphereRadius)
  54393. return false;
  54394. if (sphereCenter.z - sphereRadius > boxMax.z)
  54395. return false;
  54396. return true;
  54397. };
  54398. var getLowestRoot = (function () {
  54399. var result = { root: 0, found: false };
  54400. return function (a, b, c, maxR) {
  54401. result.root = 0;
  54402. result.found = false;
  54403. var determinant = b * b - 4.0 * a * c;
  54404. if (determinant < 0)
  54405. return result;
  54406. var sqrtD = Math.sqrt(determinant);
  54407. var r1 = (-b - sqrtD) / (2.0 * a);
  54408. var r2 = (-b + sqrtD) / (2.0 * a);
  54409. if (r1 > r2) {
  54410. var temp = r2;
  54411. r2 = r1;
  54412. r1 = temp;
  54413. }
  54414. if (r1 > 0 && r1 < maxR) {
  54415. result.root = r1;
  54416. result.found = true;
  54417. return result;
  54418. }
  54419. if (r2 > 0 && r2 < maxR) {
  54420. result.root = r2;
  54421. result.found = true;
  54422. return result;
  54423. }
  54424. return result;
  54425. };
  54426. })();
  54427. var Collider = /** @class */ (function () {
  54428. function Collider() {
  54429. this._collisionPoint = BABYLON.Vector3.Zero();
  54430. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54431. this._tempVector = BABYLON.Vector3.Zero();
  54432. this._tempVector2 = BABYLON.Vector3.Zero();
  54433. this._tempVector3 = BABYLON.Vector3.Zero();
  54434. this._tempVector4 = BABYLON.Vector3.Zero();
  54435. this._edge = BABYLON.Vector3.Zero();
  54436. this._baseToVertex = BABYLON.Vector3.Zero();
  54437. this._destinationPoint = BABYLON.Vector3.Zero();
  54438. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54439. this._displacementVector = BABYLON.Vector3.Zero();
  54440. this._radius = BABYLON.Vector3.One();
  54441. this._retry = 0;
  54442. this._basePointWorld = BABYLON.Vector3.Zero();
  54443. this._velocityWorld = BABYLON.Vector3.Zero();
  54444. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54445. this._collisionMask = -1;
  54446. }
  54447. Object.defineProperty(Collider.prototype, "collisionMask", {
  54448. get: function () {
  54449. return this._collisionMask;
  54450. },
  54451. set: function (mask) {
  54452. this._collisionMask = !isNaN(mask) ? mask : -1;
  54453. },
  54454. enumerable: true,
  54455. configurable: true
  54456. });
  54457. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54458. /**
  54459. * Gets the plane normal used to compute the sliding response (in local space)
  54460. */
  54461. get: function () {
  54462. return this._slidePlaneNormal;
  54463. },
  54464. enumerable: true,
  54465. configurable: true
  54466. });
  54467. // Methods
  54468. Collider.prototype._initialize = function (source, dir, e) {
  54469. this._velocity = dir;
  54470. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54471. this._basePoint = source;
  54472. source.multiplyToRef(this._radius, this._basePointWorld);
  54473. dir.multiplyToRef(this._radius, this._velocityWorld);
  54474. this._velocityWorldLength = this._velocityWorld.length();
  54475. this._epsilon = e;
  54476. this.collisionFound = false;
  54477. };
  54478. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54479. pa.subtractToRef(point, this._tempVector);
  54480. pb.subtractToRef(point, this._tempVector2);
  54481. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54482. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54483. if (d < 0)
  54484. return false;
  54485. pc.subtractToRef(point, this._tempVector3);
  54486. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54487. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54488. if (d < 0)
  54489. return false;
  54490. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54491. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54492. return d >= 0;
  54493. };
  54494. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54495. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54496. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54497. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54498. return false;
  54499. }
  54500. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54501. return false;
  54502. return true;
  54503. };
  54504. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54505. var t0;
  54506. var embeddedInPlane = false;
  54507. //defensive programming, actually not needed.
  54508. if (!trianglePlaneArray) {
  54509. trianglePlaneArray = [];
  54510. }
  54511. if (!trianglePlaneArray[faceIndex]) {
  54512. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54513. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54514. }
  54515. var trianglePlane = trianglePlaneArray[faceIndex];
  54516. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54517. return;
  54518. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54519. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54520. if (normalDotVelocity == 0) {
  54521. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54522. return;
  54523. embeddedInPlane = true;
  54524. t0 = 0;
  54525. }
  54526. else {
  54527. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54528. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54529. if (t0 > t1) {
  54530. var temp = t1;
  54531. t1 = t0;
  54532. t0 = temp;
  54533. }
  54534. if (t0 > 1.0 || t1 < 0.0)
  54535. return;
  54536. if (t0 < 0)
  54537. t0 = 0;
  54538. if (t0 > 1.0)
  54539. t0 = 1.0;
  54540. }
  54541. this._collisionPoint.copyFromFloats(0, 0, 0);
  54542. var found = false;
  54543. var t = 1.0;
  54544. if (!embeddedInPlane) {
  54545. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54546. this._velocity.scaleToRef(t0, this._tempVector);
  54547. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54548. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54549. found = true;
  54550. t = t0;
  54551. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54552. }
  54553. }
  54554. if (!found) {
  54555. var velocitySquaredLength = this._velocity.lengthSquared();
  54556. var a = velocitySquaredLength;
  54557. this._basePoint.subtractToRef(p1, this._tempVector);
  54558. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54559. var c = this._tempVector.lengthSquared() - 1.0;
  54560. var lowestRoot = getLowestRoot(a, b, c, t);
  54561. if (lowestRoot.found) {
  54562. t = lowestRoot.root;
  54563. found = true;
  54564. this._collisionPoint.copyFrom(p1);
  54565. }
  54566. this._basePoint.subtractToRef(p2, this._tempVector);
  54567. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54568. c = this._tempVector.lengthSquared() - 1.0;
  54569. lowestRoot = getLowestRoot(a, b, c, t);
  54570. if (lowestRoot.found) {
  54571. t = lowestRoot.root;
  54572. found = true;
  54573. this._collisionPoint.copyFrom(p2);
  54574. }
  54575. this._basePoint.subtractToRef(p3, this._tempVector);
  54576. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54577. c = this._tempVector.lengthSquared() - 1.0;
  54578. lowestRoot = getLowestRoot(a, b, c, t);
  54579. if (lowestRoot.found) {
  54580. t = lowestRoot.root;
  54581. found = true;
  54582. this._collisionPoint.copyFrom(p3);
  54583. }
  54584. p2.subtractToRef(p1, this._edge);
  54585. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54586. var edgeSquaredLength = this._edge.lengthSquared();
  54587. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54588. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54589. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54590. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54591. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54592. lowestRoot = getLowestRoot(a, b, c, t);
  54593. if (lowestRoot.found) {
  54594. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54595. if (f >= 0.0 && f <= 1.0) {
  54596. t = lowestRoot.root;
  54597. found = true;
  54598. this._edge.scaleInPlace(f);
  54599. p1.addToRef(this._edge, this._collisionPoint);
  54600. }
  54601. }
  54602. p3.subtractToRef(p2, this._edge);
  54603. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54604. edgeSquaredLength = this._edge.lengthSquared();
  54605. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54606. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54607. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54608. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54609. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54610. lowestRoot = getLowestRoot(a, b, c, t);
  54611. if (lowestRoot.found) {
  54612. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54613. if (f >= 0.0 && f <= 1.0) {
  54614. t = lowestRoot.root;
  54615. found = true;
  54616. this._edge.scaleInPlace(f);
  54617. p2.addToRef(this._edge, this._collisionPoint);
  54618. }
  54619. }
  54620. p1.subtractToRef(p3, this._edge);
  54621. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54622. edgeSquaredLength = this._edge.lengthSquared();
  54623. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54624. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54625. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54626. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54627. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54628. lowestRoot = getLowestRoot(a, b, c, t);
  54629. if (lowestRoot.found) {
  54630. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54631. if (f >= 0.0 && f <= 1.0) {
  54632. t = lowestRoot.root;
  54633. found = true;
  54634. this._edge.scaleInPlace(f);
  54635. p3.addToRef(this._edge, this._collisionPoint);
  54636. }
  54637. }
  54638. }
  54639. if (found) {
  54640. var distToCollision = t * this._velocity.length();
  54641. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54642. if (!this.intersectionPoint) {
  54643. this.intersectionPoint = this._collisionPoint.clone();
  54644. }
  54645. else {
  54646. this.intersectionPoint.copyFrom(this._collisionPoint);
  54647. }
  54648. this._nearestDistance = distToCollision;
  54649. this.collisionFound = true;
  54650. }
  54651. }
  54652. };
  54653. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54654. for (var i = indexStart; i < indexEnd; i += 3) {
  54655. var p1 = pts[indices[i] - decal];
  54656. var p2 = pts[indices[i + 1] - decal];
  54657. var p3 = pts[indices[i + 2] - decal];
  54658. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54659. }
  54660. };
  54661. Collider.prototype._getResponse = function (pos, vel) {
  54662. pos.addToRef(vel, this._destinationPoint);
  54663. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54664. this._basePoint.addToRef(vel, pos);
  54665. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54666. this._slidePlaneNormal.normalize();
  54667. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54668. pos.addInPlace(this._displacementVector);
  54669. this.intersectionPoint.addInPlace(this._displacementVector);
  54670. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54671. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54672. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54673. };
  54674. return Collider;
  54675. }());
  54676. BABYLON.Collider = Collider;
  54677. })(BABYLON || (BABYLON = {}));
  54678. //# sourceMappingURL=babylon.collider.js.map
  54679. var BABYLON;
  54680. (function (BABYLON) {
  54681. //WebWorker code will be inserted to this variable.
  54682. BABYLON.CollisionWorker = "";
  54683. /** Defines supported task for worker process */
  54684. var WorkerTaskType;
  54685. (function (WorkerTaskType) {
  54686. /** Initialization */
  54687. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54688. /** Update of geometry */
  54689. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54690. /** Evaluate collision */
  54691. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54692. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54693. /** Defines kind of replies returned by worker */
  54694. var WorkerReplyType;
  54695. (function (WorkerReplyType) {
  54696. /** Success */
  54697. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54698. /** Unkown error */
  54699. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54700. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54701. var CollisionCoordinatorWorker = /** @class */ (function () {
  54702. function CollisionCoordinatorWorker() {
  54703. var _this = this;
  54704. this._scaledPosition = BABYLON.Vector3.Zero();
  54705. this._scaledVelocity = BABYLON.Vector3.Zero();
  54706. this.onMeshUpdated = function (transformNode) {
  54707. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54708. };
  54709. this.onGeometryUpdated = function (geometry) {
  54710. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54711. };
  54712. this._afterRender = function () {
  54713. if (!_this._init)
  54714. return;
  54715. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54716. return;
  54717. }
  54718. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54719. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54720. if (_this._runningUpdated > 4) {
  54721. return;
  54722. }
  54723. ++_this._runningUpdated;
  54724. var payload = {
  54725. updatedMeshes: _this._addUpdateMeshesList,
  54726. updatedGeometries: _this._addUpdateGeometriesList,
  54727. removedGeometries: _this._toRemoveGeometryArray,
  54728. removedMeshes: _this._toRemoveMeshesArray
  54729. };
  54730. var message = {
  54731. payload: payload,
  54732. taskType: WorkerTaskType.UPDATE
  54733. };
  54734. var serializable = [];
  54735. for (var id in payload.updatedGeometries) {
  54736. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54737. //prepare transferables
  54738. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54739. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54740. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54741. }
  54742. }
  54743. _this._worker.postMessage(message, serializable);
  54744. _this._addUpdateMeshesList = {};
  54745. _this._addUpdateGeometriesList = {};
  54746. _this._toRemoveGeometryArray = [];
  54747. _this._toRemoveMeshesArray = [];
  54748. };
  54749. this._onMessageFromWorker = function (e) {
  54750. var returnData = e.data;
  54751. if (returnData.error != WorkerReplyType.SUCCESS) {
  54752. //TODO what errors can be returned from the worker?
  54753. BABYLON.Tools.Warn("error returned from worker!");
  54754. return;
  54755. }
  54756. switch (returnData.taskType) {
  54757. case WorkerTaskType.INIT:
  54758. _this._init = true;
  54759. //Update the worked with ALL of the scene's current state
  54760. _this._scene.meshes.forEach(function (mesh) {
  54761. _this.onMeshAdded(mesh);
  54762. });
  54763. _this._scene.getGeometries().forEach(function (geometry) {
  54764. _this.onGeometryAdded(geometry);
  54765. });
  54766. break;
  54767. case WorkerTaskType.UPDATE:
  54768. _this._runningUpdated--;
  54769. break;
  54770. case WorkerTaskType.COLLIDE:
  54771. var returnPayload = returnData.payload;
  54772. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54773. return;
  54774. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54775. if (callback) {
  54776. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54777. if (mesh) {
  54778. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54779. }
  54780. }
  54781. //cleanup
  54782. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54783. break;
  54784. }
  54785. };
  54786. this._collisionsCallbackArray = [];
  54787. this._init = false;
  54788. this._runningUpdated = 0;
  54789. this._addUpdateMeshesList = {};
  54790. this._addUpdateGeometriesList = {};
  54791. this._toRemoveGeometryArray = [];
  54792. this._toRemoveMeshesArray = [];
  54793. }
  54794. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54795. if (!this._init)
  54796. return;
  54797. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54798. return;
  54799. position.divideToRef(collider._radius, this._scaledPosition);
  54800. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54801. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54802. var payload = {
  54803. collider: {
  54804. position: this._scaledPosition.asArray(),
  54805. velocity: this._scaledVelocity.asArray(),
  54806. radius: collider._radius.asArray()
  54807. },
  54808. collisionId: collisionIndex,
  54809. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54810. maximumRetry: maximumRetry
  54811. };
  54812. var message = {
  54813. payload: payload,
  54814. taskType: WorkerTaskType.COLLIDE
  54815. };
  54816. this._worker.postMessage(message);
  54817. };
  54818. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54819. this._scene = scene;
  54820. this._scene.registerAfterRender(this._afterRender);
  54821. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54822. this._worker = new Worker(workerUrl);
  54823. this._worker.onmessage = this._onMessageFromWorker;
  54824. var message = {
  54825. payload: {},
  54826. taskType: WorkerTaskType.INIT
  54827. };
  54828. this._worker.postMessage(message);
  54829. };
  54830. CollisionCoordinatorWorker.prototype.destroy = function () {
  54831. this._scene.unregisterAfterRender(this._afterRender);
  54832. this._worker.terminate();
  54833. };
  54834. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54835. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54836. this.onMeshUpdated(mesh);
  54837. };
  54838. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54839. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54840. };
  54841. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54842. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54843. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54844. this.onGeometryUpdated(geometry);
  54845. };
  54846. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54847. this._toRemoveGeometryArray.push(geometry.id);
  54848. };
  54849. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54850. var submeshes = [];
  54851. if (mesh.subMeshes) {
  54852. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54853. var boundingInfo = sm.getBoundingInfo();
  54854. return {
  54855. position: idx,
  54856. verticesStart: sm.verticesStart,
  54857. verticesCount: sm.verticesCount,
  54858. indexStart: sm.indexStart,
  54859. indexCount: sm.indexCount,
  54860. hasMaterial: !!sm.getMaterial(),
  54861. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54862. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54863. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54864. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54865. };
  54866. });
  54867. }
  54868. var geometryId = null;
  54869. if (mesh instanceof BABYLON.Mesh) {
  54870. var geometry = mesh.geometry;
  54871. geometryId = geometry ? geometry.id : null;
  54872. }
  54873. else if (mesh instanceof BABYLON.InstancedMesh) {
  54874. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54875. geometryId = geometry ? geometry.id : null;
  54876. }
  54877. var boundingInfo = mesh.getBoundingInfo();
  54878. return {
  54879. uniqueId: mesh.uniqueId,
  54880. id: mesh.id,
  54881. name: mesh.name,
  54882. geometryId: geometryId,
  54883. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54884. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54885. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54886. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54887. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54888. subMeshes: submeshes,
  54889. checkCollisions: mesh.checkCollisions
  54890. };
  54891. };
  54892. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54893. return {
  54894. id: geometry.id,
  54895. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54896. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54897. indices: new Uint32Array(geometry.getIndices() || []),
  54898. };
  54899. };
  54900. return CollisionCoordinatorWorker;
  54901. }());
  54902. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54903. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54904. function CollisionCoordinatorLegacy() {
  54905. this._scaledPosition = BABYLON.Vector3.Zero();
  54906. this._scaledVelocity = BABYLON.Vector3.Zero();
  54907. this._finalPosition = BABYLON.Vector3.Zero();
  54908. }
  54909. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54910. position.divideToRef(collider._radius, this._scaledPosition);
  54911. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54912. collider.collidedMesh = null;
  54913. collider._retry = 0;
  54914. collider._initialVelocity = this._scaledVelocity;
  54915. collider._initialPosition = this._scaledPosition;
  54916. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54917. this._finalPosition.multiplyInPlace(collider._radius);
  54918. //run the callback
  54919. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54920. };
  54921. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54922. this._scene = scene;
  54923. };
  54924. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54925. //Legacy need no destruction method.
  54926. };
  54927. //No update in legacy mode
  54928. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54929. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54930. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54931. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54932. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54933. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54934. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54935. if (excludedMesh === void 0) { excludedMesh = null; }
  54936. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54937. if (collider._retry >= maximumRetry) {
  54938. finalPosition.copyFrom(position);
  54939. return;
  54940. }
  54941. // Check if this is a mesh else camera or -1
  54942. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54943. collider._initialize(position, velocity, closeDistance);
  54944. // Check all meshes
  54945. for (var index = 0; index < this._scene.meshes.length; index++) {
  54946. var mesh = this._scene.meshes[index];
  54947. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54948. mesh._checkCollision(collider);
  54949. }
  54950. }
  54951. if (!collider.collisionFound) {
  54952. position.addToRef(velocity, finalPosition);
  54953. return;
  54954. }
  54955. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54956. collider._getResponse(position, velocity);
  54957. }
  54958. if (velocity.length() <= closeDistance) {
  54959. finalPosition.copyFrom(position);
  54960. return;
  54961. }
  54962. collider._retry++;
  54963. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54964. };
  54965. return CollisionCoordinatorLegacy;
  54966. }());
  54967. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54968. })(BABYLON || (BABYLON = {}));
  54969. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54970. var BABYLON;
  54971. (function (BABYLON) {
  54972. /**
  54973. * A particle represents one of the element emitted by a particle system.
  54974. * This is mainly define by its coordinates, direction, velocity and age.
  54975. */
  54976. var Particle = /** @class */ (function () {
  54977. /**
  54978. * Creates a new instance Particle
  54979. * @param particleSystem the particle system the particle belongs to
  54980. */
  54981. function Particle(
  54982. /**
  54983. * particleSystem the particle system the particle belongs to.
  54984. */
  54985. particleSystem) {
  54986. this.particleSystem = particleSystem;
  54987. /**
  54988. * The world position of the particle in the scene.
  54989. */
  54990. this.position = BABYLON.Vector3.Zero();
  54991. /**
  54992. * The world direction of the particle in the scene.
  54993. */
  54994. this.direction = BABYLON.Vector3.Zero();
  54995. /**
  54996. * The color of the particle.
  54997. */
  54998. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54999. /**
  55000. * The color change of the particle per step.
  55001. */
  55002. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55003. /**
  55004. * Defines how long will the life of the particle be.
  55005. */
  55006. this.lifeTime = 1.0;
  55007. /**
  55008. * The current age of the particle.
  55009. */
  55010. this.age = 0;
  55011. /**
  55012. * The current size of the particle.
  55013. */
  55014. this.size = 0;
  55015. /**
  55016. * The current scale of the particle.
  55017. */
  55018. this.scale = new BABYLON.Vector2(1, 1);
  55019. /**
  55020. * The current angle of the particle.
  55021. */
  55022. this.angle = 0;
  55023. /**
  55024. * Defines how fast is the angle changing.
  55025. */
  55026. this.angularSpeed = 0;
  55027. /**
  55028. * Defines the cell index used by the particle to be rendered from a sprite.
  55029. */
  55030. this.cellIndex = 0;
  55031. /** @hidden */
  55032. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55033. /** @hidden */
  55034. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55035. /** @hidden */
  55036. this._currentSize1 = 0;
  55037. /** @hidden */
  55038. this._currentSize2 = 0;
  55039. /** @hidden */
  55040. this._currentAngularSpeed1 = 0;
  55041. /** @hidden */
  55042. this._currentAngularSpeed2 = 0;
  55043. /** @hidden */
  55044. this._currentVelocity1 = 0;
  55045. /** @hidden */
  55046. this._currentVelocity2 = 0;
  55047. if (!this.particleSystem.isAnimationSheetEnabled) {
  55048. return;
  55049. }
  55050. this.updateCellInfoFromSystem();
  55051. }
  55052. Particle.prototype.updateCellInfoFromSystem = function () {
  55053. this.cellIndex = this.particleSystem.startSpriteCellID;
  55054. };
  55055. /**
  55056. * Defines how the sprite cell index is updated for the particle
  55057. */
  55058. Particle.prototype.updateCellIndex = function () {
  55059. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55060. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55061. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55062. };
  55063. /**
  55064. * Copy the properties of particle to another one.
  55065. * @param other the particle to copy the information to.
  55066. */
  55067. Particle.prototype.copyTo = function (other) {
  55068. other.position.copyFrom(this.position);
  55069. if (this._initialDirection) {
  55070. if (other._initialDirection) {
  55071. other._initialDirection.copyFrom(this._initialDirection);
  55072. }
  55073. else {
  55074. other._initialDirection = this._initialDirection.clone();
  55075. }
  55076. }
  55077. else {
  55078. other._initialDirection = null;
  55079. }
  55080. other.direction.copyFrom(this.direction);
  55081. other.color.copyFrom(this.color);
  55082. other.colorStep.copyFrom(this.colorStep);
  55083. other.lifeTime = this.lifeTime;
  55084. other.age = this.age;
  55085. other.size = this.size;
  55086. other.scale.copyFrom(this.scale);
  55087. other.angle = this.angle;
  55088. other.angularSpeed = this.angularSpeed;
  55089. other.particleSystem = this.particleSystem;
  55090. other.cellIndex = this.cellIndex;
  55091. if (this._currentColorGradient) {
  55092. other._currentColorGradient = this._currentColorGradient;
  55093. other._currentColor1.copyFrom(this._currentColor1);
  55094. other._currentColor2.copyFrom(this._currentColor2);
  55095. }
  55096. if (this._currentSizeGradient) {
  55097. other._currentSizeGradient = this._currentSizeGradient;
  55098. other._currentSize1 = this._currentSize1;
  55099. other._currentSize2 = this._currentSize2;
  55100. }
  55101. if (this._currentAngularSpeedGradient) {
  55102. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55103. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55104. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55105. }
  55106. if (this._currentVelocityGradient) {
  55107. other._currentVelocityGradient = this._currentVelocityGradient;
  55108. other._currentVelocity1 = this._currentVelocity1;
  55109. other._currentVelocity2 = this._currentVelocity2;
  55110. }
  55111. if (this.particleSystem.isAnimationSheetEnabled) {
  55112. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55113. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55114. }
  55115. };
  55116. return Particle;
  55117. }());
  55118. BABYLON.Particle = Particle;
  55119. })(BABYLON || (BABYLON = {}));
  55120. //# sourceMappingURL=babylon.particle.js.map
  55121. var BABYLON;
  55122. (function (BABYLON) {
  55123. /**
  55124. * This represents the base class for particle system in Babylon.
  55125. * 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.
  55126. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55127. * @example https://doc.babylonjs.com/babylon101/particles
  55128. */
  55129. var BaseParticleSystem = /** @class */ (function () {
  55130. /**
  55131. * Instantiates a particle system.
  55132. * 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.
  55133. * @param name The name of the particle system
  55134. */
  55135. function BaseParticleSystem(name) {
  55136. /**
  55137. * List of animations used by the particle system.
  55138. */
  55139. this.animations = [];
  55140. /**
  55141. * The rendering group used by the Particle system to chose when to render.
  55142. */
  55143. this.renderingGroupId = 0;
  55144. /**
  55145. * The emitter represents the Mesh or position we are attaching the particle system to.
  55146. */
  55147. this.emitter = null;
  55148. /**
  55149. * The maximum number of particles to emit per frame
  55150. */
  55151. this.emitRate = 10;
  55152. /**
  55153. * If you want to launch only a few particles at once, that can be done, as well.
  55154. */
  55155. this.manualEmitCount = -1;
  55156. /**
  55157. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55158. */
  55159. this.updateSpeed = 0.01;
  55160. /**
  55161. * The amount of time the particle system is running (depends of the overall update speed).
  55162. */
  55163. this.targetStopDuration = 0;
  55164. /**
  55165. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55166. */
  55167. this.disposeOnStop = false;
  55168. /**
  55169. * Minimum power of emitting particles.
  55170. */
  55171. this.minEmitPower = 1;
  55172. /**
  55173. * Maximum power of emitting particles.
  55174. */
  55175. this.maxEmitPower = 1;
  55176. /**
  55177. * Minimum life time of emitting particles.
  55178. */
  55179. this.minLifeTime = 1;
  55180. /**
  55181. * Maximum life time of emitting particles.
  55182. */
  55183. this.maxLifeTime = 1;
  55184. /**
  55185. * Minimum Size of emitting particles.
  55186. */
  55187. this.minSize = 1;
  55188. /**
  55189. * Maximum Size of emitting particles.
  55190. */
  55191. this.maxSize = 1;
  55192. /**
  55193. * Minimum scale of emitting particles on X axis.
  55194. */
  55195. this.minScaleX = 1;
  55196. /**
  55197. * Maximum scale of emitting particles on X axis.
  55198. */
  55199. this.maxScaleX = 1;
  55200. /**
  55201. * Minimum scale of emitting particles on Y axis.
  55202. */
  55203. this.minScaleY = 1;
  55204. /**
  55205. * Maximum scale of emitting particles on Y axis.
  55206. */
  55207. this.maxScaleY = 1;
  55208. /**
  55209. * Gets or sets the minimal initial rotation in radians.
  55210. */
  55211. this.minInitialRotation = 0;
  55212. /**
  55213. * Gets or sets the maximal initial rotation in radians.
  55214. */
  55215. this.maxInitialRotation = 0;
  55216. /**
  55217. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55218. */
  55219. this.minAngularSpeed = 0;
  55220. /**
  55221. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55222. */
  55223. this.maxAngularSpeed = 0;
  55224. /**
  55225. * The layer mask we are rendering the particles through.
  55226. */
  55227. this.layerMask = 0x0FFFFFFF;
  55228. /**
  55229. * This can help using your own shader to render the particle system.
  55230. * The according effect will be created
  55231. */
  55232. this.customShader = null;
  55233. /**
  55234. * By default particle system starts as soon as they are created. This prevents the
  55235. * automatic start to happen and let you decide when to start emitting particles.
  55236. */
  55237. this.preventAutoStart = false;
  55238. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55239. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55240. /**
  55241. * Callback triggered when the particle animation is ending.
  55242. */
  55243. this.onAnimationEnd = null;
  55244. /**
  55245. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55246. */
  55247. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55248. /**
  55249. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55250. * to override the particles.
  55251. */
  55252. this.forceDepthWrite = false;
  55253. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55254. this.preWarmCycles = 0;
  55255. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55256. this.preWarmStepOffset = 1;
  55257. /**
  55258. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55259. */
  55260. this.spriteCellChangeSpeed = 1;
  55261. /**
  55262. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55263. */
  55264. this.startSpriteCellID = 0;
  55265. /**
  55266. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55267. */
  55268. this.endSpriteCellID = 0;
  55269. /**
  55270. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55271. */
  55272. this.spriteCellWidth = 0;
  55273. /**
  55274. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55275. */
  55276. this.spriteCellHeight = 0;
  55277. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55278. this.translationPivot = new BABYLON.Vector2(0, 0);
  55279. /**
  55280. * You can use gravity if you want to give an orientation to your particles.
  55281. */
  55282. this.gravity = BABYLON.Vector3.Zero();
  55283. this._colorGradients = null;
  55284. this._sizeGradients = null;
  55285. this._lifeTimeGradients = null;
  55286. this._angularSpeedGradients = null;
  55287. this._velocityGradients = null;
  55288. /**
  55289. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55290. */
  55291. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55292. /**
  55293. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55294. */
  55295. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55296. /**
  55297. * Color the particle will have at the end of its lifetime
  55298. */
  55299. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55300. /**
  55301. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55302. */
  55303. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55304. /**
  55305. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55306. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55307. */
  55308. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55309. this._isBillboardBased = true;
  55310. this.id = name;
  55311. this.name = name;
  55312. }
  55313. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55314. /**
  55315. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55316. */
  55317. get: function () {
  55318. return this._isAnimationSheetEnabled;
  55319. },
  55320. set: function (value) {
  55321. if (this._isAnimationSheetEnabled == value) {
  55322. return;
  55323. }
  55324. this._isAnimationSheetEnabled = value;
  55325. this._reset();
  55326. },
  55327. enumerable: true,
  55328. configurable: true
  55329. });
  55330. /**
  55331. * Gets the current list of color gradients.
  55332. * You must use addColorGradient and removeColorGradient to udpate this list
  55333. * @returns the list of color gradients
  55334. */
  55335. BaseParticleSystem.prototype.getColorGradients = function () {
  55336. return this._colorGradients;
  55337. };
  55338. /**
  55339. * Gets the current list of size gradients.
  55340. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55341. * @returns the list of size gradients
  55342. */
  55343. BaseParticleSystem.prototype.getSizeGradients = function () {
  55344. return this._sizeGradients;
  55345. };
  55346. /**
  55347. * Gets the current list of life time gradients.
  55348. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55349. * @returns the list of life time gradients
  55350. */
  55351. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55352. return this._lifeTimeGradients;
  55353. };
  55354. /**
  55355. * Gets the current list of angular speed gradients.
  55356. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55357. * @returns the list of angular speed gradients
  55358. */
  55359. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55360. return this._angularSpeedGradients;
  55361. };
  55362. /**
  55363. * Gets the current list of velocity gradients.
  55364. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55365. * @returns the list of velocity gradients
  55366. */
  55367. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55368. return this._velocityGradients;
  55369. };
  55370. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55371. /**
  55372. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55373. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55374. */
  55375. get: function () {
  55376. if (this.particleEmitterType.direction1) {
  55377. return this.particleEmitterType.direction1;
  55378. }
  55379. return BABYLON.Vector3.Zero();
  55380. },
  55381. set: function (value) {
  55382. if (this.particleEmitterType.direction1) {
  55383. this.particleEmitterType.direction1 = value;
  55384. }
  55385. },
  55386. enumerable: true,
  55387. configurable: true
  55388. });
  55389. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55390. /**
  55391. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55392. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55393. */
  55394. get: function () {
  55395. if (this.particleEmitterType.direction2) {
  55396. return this.particleEmitterType.direction2;
  55397. }
  55398. return BABYLON.Vector3.Zero();
  55399. },
  55400. set: function (value) {
  55401. if (this.particleEmitterType.direction2) {
  55402. this.particleEmitterType.direction2 = value;
  55403. }
  55404. },
  55405. enumerable: true,
  55406. configurable: true
  55407. });
  55408. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55409. /**
  55410. * 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.
  55411. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55412. */
  55413. get: function () {
  55414. if (this.particleEmitterType.minEmitBox) {
  55415. return this.particleEmitterType.minEmitBox;
  55416. }
  55417. return BABYLON.Vector3.Zero();
  55418. },
  55419. set: function (value) {
  55420. if (this.particleEmitterType.minEmitBox) {
  55421. this.particleEmitterType.minEmitBox = value;
  55422. }
  55423. },
  55424. enumerable: true,
  55425. configurable: true
  55426. });
  55427. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55428. /**
  55429. * 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.
  55430. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55431. */
  55432. get: function () {
  55433. if (this.particleEmitterType.maxEmitBox) {
  55434. return this.particleEmitterType.maxEmitBox;
  55435. }
  55436. return BABYLON.Vector3.Zero();
  55437. },
  55438. set: function (value) {
  55439. if (this.particleEmitterType.maxEmitBox) {
  55440. this.particleEmitterType.maxEmitBox = value;
  55441. }
  55442. },
  55443. enumerable: true,
  55444. configurable: true
  55445. });
  55446. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55447. /**
  55448. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55449. */
  55450. get: function () {
  55451. return this._isBillboardBased;
  55452. },
  55453. set: function (value) {
  55454. if (this._isBillboardBased === value) {
  55455. return;
  55456. }
  55457. this._isBillboardBased = value;
  55458. this._reset();
  55459. },
  55460. enumerable: true,
  55461. configurable: true
  55462. });
  55463. /** @hidden */
  55464. BaseParticleSystem.prototype._reset = function () {
  55465. };
  55466. /**
  55467. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55468. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55469. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55470. * @returns the emitter
  55471. */
  55472. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55473. var particleEmitter = new BABYLON.PointParticleEmitter();
  55474. particleEmitter.direction1 = direction1;
  55475. particleEmitter.direction2 = direction2;
  55476. this.particleEmitterType = particleEmitter;
  55477. return particleEmitter;
  55478. };
  55479. /**
  55480. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55481. * @param radius The radius of the hemisphere to emit from
  55482. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55483. * @returns the emitter
  55484. */
  55485. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55486. if (radius === void 0) { radius = 1; }
  55487. if (radiusRange === void 0) { radiusRange = 1; }
  55488. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55489. this.particleEmitterType = particleEmitter;
  55490. return particleEmitter;
  55491. };
  55492. /**
  55493. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55494. * @param radius The radius of the sphere to emit from
  55495. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55496. * @returns the emitter
  55497. */
  55498. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55499. if (radius === void 0) { radius = 1; }
  55500. if (radiusRange === void 0) { radiusRange = 1; }
  55501. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55502. this.particleEmitterType = particleEmitter;
  55503. return particleEmitter;
  55504. };
  55505. /**
  55506. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55507. * @param radius The radius of the sphere to emit from
  55508. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55509. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55510. * @returns the emitter
  55511. */
  55512. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55513. if (radius === void 0) { radius = 1; }
  55514. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55515. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55516. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55517. this.particleEmitterType = particleEmitter;
  55518. return particleEmitter;
  55519. };
  55520. /**
  55521. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  55522. * @param radius The radius of the cone to emit from
  55523. * @param angle The base angle of the cone
  55524. * @returns the emitter
  55525. */
  55526. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55527. if (radius === void 0) { radius = 1; }
  55528. if (angle === void 0) { angle = Math.PI / 4; }
  55529. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55530. this.particleEmitterType = particleEmitter;
  55531. return particleEmitter;
  55532. };
  55533. /**
  55534. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55535. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55536. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55537. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55538. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55539. * @returns the emitter
  55540. */
  55541. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55542. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55543. this.particleEmitterType = particleEmitter;
  55544. this.direction1 = direction1;
  55545. this.direction2 = direction2;
  55546. this.minEmitBox = minEmitBox;
  55547. this.maxEmitBox = maxEmitBox;
  55548. return particleEmitter;
  55549. };
  55550. /**
  55551. * Source color is added to the destination color without alpha affecting the result.
  55552. */
  55553. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  55554. /**
  55555. * Blend current color and particle color using particle’s alpha.
  55556. */
  55557. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  55558. /**
  55559. * Add current color and particle color multiplied by particle’s alpha.
  55560. */
  55561. BaseParticleSystem.BLENDMODE_ADD = 2;
  55562. return BaseParticleSystem;
  55563. }());
  55564. BABYLON.BaseParticleSystem = BaseParticleSystem;
  55565. })(BABYLON || (BABYLON = {}));
  55566. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  55567. var BABYLON;
  55568. (function (BABYLON) {
  55569. /**
  55570. * This represents a particle system in Babylon.
  55571. * 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.
  55572. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55573. * @example https://doc.babylonjs.com/babylon101/particles
  55574. */
  55575. var ParticleSystem = /** @class */ (function (_super) {
  55576. __extends(ParticleSystem, _super);
  55577. /**
  55578. * Instantiates a particle system.
  55579. * 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.
  55580. * @param name The name of the particle system
  55581. * @param capacity The max number of particles alive at the same time
  55582. * @param scene The scene the particle system belongs to
  55583. * @param customEffect a custom effect used to change the way particles are rendered by default
  55584. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55585. * @param epsilon Offset used to render the particles
  55586. */
  55587. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55588. if (customEffect === void 0) { customEffect = null; }
  55589. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55590. if (epsilon === void 0) { epsilon = 0.01; }
  55591. var _this = _super.call(this, name) || this;
  55592. /**
  55593. * An event triggered when the system is disposed
  55594. */
  55595. _this.onDisposeObservable = new BABYLON.Observable();
  55596. _this._particles = new Array();
  55597. _this._stockParticles = new Array();
  55598. _this._newPartsExcess = 0;
  55599. _this._vertexBuffers = {};
  55600. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55601. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55602. _this._scaledDirection = BABYLON.Vector3.Zero();
  55603. _this._scaledGravity = BABYLON.Vector3.Zero();
  55604. _this._currentRenderId = -1;
  55605. _this._useInstancing = false;
  55606. _this._started = false;
  55607. _this._stopped = false;
  55608. _this._actualFrame = 0;
  55609. // start of sub system methods
  55610. /**
  55611. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55612. * Its lifetime will start back at 0.
  55613. */
  55614. _this.recycleParticle = function (particle) {
  55615. var lastParticle = _this._particles.pop();
  55616. if (lastParticle !== particle) {
  55617. lastParticle.copyTo(particle);
  55618. }
  55619. _this._stockParticles.push(lastParticle);
  55620. };
  55621. _this._createParticle = function () {
  55622. var particle;
  55623. if (_this._stockParticles.length !== 0) {
  55624. particle = _this._stockParticles.pop();
  55625. particle.age = 0;
  55626. particle._currentColorGradient = null;
  55627. particle.cellIndex = _this.startSpriteCellID;
  55628. }
  55629. else {
  55630. particle = new BABYLON.Particle(_this);
  55631. }
  55632. return particle;
  55633. };
  55634. _this._emitFromParticle = function (particle) {
  55635. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55636. return;
  55637. }
  55638. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55639. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55640. subSystem._rootParticleSystem = _this;
  55641. _this.activeSubSystems.push(subSystem);
  55642. subSystem.start();
  55643. };
  55644. _this._capacity = capacity;
  55645. _this._epsilon = epsilon;
  55646. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55647. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55648. _this._customEffect = customEffect;
  55649. _this._scene.particleSystems.push(_this);
  55650. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  55651. _this._createIndexBuffer();
  55652. _this._createVertexBuffers();
  55653. // Default emitter type
  55654. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55655. _this.updateFunction = function (particles) {
  55656. var noiseTextureData = null;
  55657. var noiseTextureSize = null;
  55658. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55659. noiseTextureData = (_this.noiseTexture.readPixels());
  55660. noiseTextureSize = _this.noiseTexture.getSize();
  55661. }
  55662. var _loop_1 = function () {
  55663. particle = particles[index];
  55664. particle.age += _this._scaledUpdateSpeed;
  55665. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55666. _this._emitFromParticle(particle);
  55667. _this.recycleParticle(particle);
  55668. index--;
  55669. return "continue";
  55670. }
  55671. else {
  55672. var ratio = particle.age / particle.lifeTime;
  55673. // Color
  55674. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55675. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55676. if (currentGradient !== particle._currentColorGradient) {
  55677. particle._currentColor1.copyFrom(particle._currentColor2);
  55678. nextGradient.getColorToRef(particle._currentColor2);
  55679. particle._currentColorGradient = currentGradient;
  55680. }
  55681. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55682. });
  55683. }
  55684. else {
  55685. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55686. particle.color.addInPlace(_this._scaledColorStep);
  55687. if (particle.color.a < 0) {
  55688. particle.color.a = 0;
  55689. }
  55690. }
  55691. // Angular speed
  55692. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55693. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55694. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55695. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55696. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55697. particle._currentAngularSpeedGradient = currentGradient;
  55698. }
  55699. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55700. });
  55701. }
  55702. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55703. // Direction
  55704. var directionScale_1 = _this._scaledUpdateSpeed;
  55705. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55706. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55707. if (currentGradient !== particle._currentVelocityGradient) {
  55708. particle._currentVelocity1 = particle._currentVelocity2;
  55709. particle._currentVelocity2 = nextGradient.getFactor();
  55710. particle._currentVelocityGradient = currentGradient;
  55711. }
  55712. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55713. });
  55714. }
  55715. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55716. particle.position.addInPlace(_this._scaledDirection);
  55717. // Noise
  55718. if (noiseTextureData && noiseTextureSize) {
  55719. var localPosition = BABYLON.Tmp.Vector3[0];
  55720. var emitterPosition = BABYLON.Tmp.Vector3[1];
  55721. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  55722. particle.position.subtractToRef(emitterPosition, localPosition);
  55723. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55724. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55725. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55726. var force = BABYLON.Tmp.Vector3[0];
  55727. var scaledForce = BABYLON.Tmp.Vector3[1];
  55728. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55729. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55730. particle.direction.addInPlace(scaledForce);
  55731. }
  55732. // Gravity
  55733. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55734. particle.direction.addInPlace(_this._scaledGravity);
  55735. // Size
  55736. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55737. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55738. if (currentGradient !== particle._currentSizeGradient) {
  55739. particle._currentSize1 = particle._currentSize2;
  55740. particle._currentSize2 = nextGradient.getFactor();
  55741. particle._currentSizeGradient = currentGradient;
  55742. }
  55743. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55744. });
  55745. }
  55746. if (_this._isAnimationSheetEnabled) {
  55747. particle.updateCellIndex();
  55748. }
  55749. }
  55750. };
  55751. var particle;
  55752. for (var index = 0; index < particles.length; index++) {
  55753. _loop_1();
  55754. }
  55755. };
  55756. return _this;
  55757. }
  55758. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55759. /**
  55760. * Sets a callback that will be triggered when the system is disposed
  55761. */
  55762. set: function (callback) {
  55763. if (this._onDisposeObserver) {
  55764. this.onDisposeObservable.remove(this._onDisposeObserver);
  55765. }
  55766. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55767. },
  55768. enumerable: true,
  55769. configurable: true
  55770. });
  55771. /**
  55772. * Get hosting scene
  55773. * @returns the scene
  55774. */
  55775. ParticleSystem.prototype.getScene = function () {
  55776. return this._scene;
  55777. };
  55778. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55779. //end of Sub-emitter
  55780. /**
  55781. * Gets the current list of active particles
  55782. */
  55783. get: function () {
  55784. return this._particles;
  55785. },
  55786. enumerable: true,
  55787. configurable: true
  55788. });
  55789. /**
  55790. * Returns the string "ParticleSystem"
  55791. * @returns a string containing the class name
  55792. */
  55793. ParticleSystem.prototype.getClassName = function () {
  55794. return "ParticleSystem";
  55795. };
  55796. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55797. var newGradient = new BABYLON.FactorGradient();
  55798. newGradient.gradient = gradient;
  55799. newGradient.factor1 = factor;
  55800. newGradient.factor2 = factor2;
  55801. factorGradients.push(newGradient);
  55802. factorGradients.sort(function (a, b) {
  55803. if (a.gradient < b.gradient) {
  55804. return -1;
  55805. }
  55806. else if (a.gradient > b.gradient) {
  55807. return 1;
  55808. }
  55809. return 0;
  55810. });
  55811. };
  55812. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55813. if (!factorGradients) {
  55814. return;
  55815. }
  55816. var index = 0;
  55817. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55818. var factorGradient = factorGradients_1[_i];
  55819. if (factorGradient.gradient === gradient) {
  55820. factorGradients.splice(index, 1);
  55821. break;
  55822. }
  55823. index++;
  55824. }
  55825. };
  55826. /**
  55827. * Adds a new life time gradient
  55828. * @param gradient defines the gradient to use (between 0 and 1)
  55829. * @param factor defines the life time factor to affect to the specified gradient
  55830. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55831. * @returns the current particle system
  55832. */
  55833. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55834. if (!this._lifeTimeGradients) {
  55835. this._lifeTimeGradients = [];
  55836. }
  55837. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55838. return this;
  55839. };
  55840. /**
  55841. * Remove a specific life time gradient
  55842. * @param gradient defines the gradient to remove
  55843. * @returns the current particle system
  55844. */
  55845. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55846. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55847. return this;
  55848. };
  55849. /**
  55850. * Adds a new size gradient
  55851. * @param gradient defines the gradient to use (between 0 and 1)
  55852. * @param factor defines the size factor to affect to the specified gradient
  55853. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55854. * @returns the current particle system
  55855. */
  55856. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55857. if (!this._sizeGradients) {
  55858. this._sizeGradients = [];
  55859. }
  55860. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55861. return this;
  55862. };
  55863. /**
  55864. * Remove a specific size gradient
  55865. * @param gradient defines the gradient to remove
  55866. * @returns the current particle system
  55867. */
  55868. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55869. this._removeFactorGradient(this._sizeGradients, gradient);
  55870. return this;
  55871. };
  55872. /**
  55873. * Adds a new angular speed gradient
  55874. * @param gradient defines the gradient to use (between 0 and 1)
  55875. * @param factor defines the size factor to affect to the specified gradient
  55876. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55877. * @returns the current particle system
  55878. */
  55879. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55880. if (!this._angularSpeedGradients) {
  55881. this._angularSpeedGradients = [];
  55882. }
  55883. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55884. return this;
  55885. };
  55886. /**
  55887. * Remove a specific angular speed gradient
  55888. * @param gradient defines the gradient to remove
  55889. * @returns the current particle system
  55890. */
  55891. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55892. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55893. return this;
  55894. };
  55895. /**
  55896. * Adds a new velocity gradient
  55897. * @param gradient defines the gradient to use (between 0 and 1)
  55898. * @param factor defines the size factor to affect to the specified gradient
  55899. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55900. * @returns the current particle system
  55901. */
  55902. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55903. if (!this._velocityGradients) {
  55904. this._velocityGradients = [];
  55905. }
  55906. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55907. return this;
  55908. };
  55909. /**
  55910. * Remove a specific velocity gradient
  55911. * @param gradient defines the gradient to remove
  55912. * @returns the current particle system
  55913. */
  55914. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55915. this._removeFactorGradient(this._velocityGradients, gradient);
  55916. return this;
  55917. };
  55918. /**
  55919. * Adds a new color gradient
  55920. * @param gradient defines the gradient to use (between 0 and 1)
  55921. * @param color defines the color to affect to the specified gradient
  55922. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55923. */
  55924. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55925. if (!this._colorGradients) {
  55926. this._colorGradients = [];
  55927. }
  55928. var colorGradient = new BABYLON.ColorGradient();
  55929. colorGradient.gradient = gradient;
  55930. colorGradient.color1 = color;
  55931. colorGradient.color2 = color2;
  55932. this._colorGradients.push(colorGradient);
  55933. this._colorGradients.sort(function (a, b) {
  55934. if (a.gradient < b.gradient) {
  55935. return -1;
  55936. }
  55937. else if (a.gradient > b.gradient) {
  55938. return 1;
  55939. }
  55940. return 0;
  55941. });
  55942. return this;
  55943. };
  55944. /**
  55945. * Remove a specific color gradient
  55946. * @param gradient defines the gradient to remove
  55947. */
  55948. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55949. if (!this._colorGradients) {
  55950. return this;
  55951. }
  55952. var index = 0;
  55953. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55954. var colorGradient = _a[_i];
  55955. if (colorGradient.gradient === gradient) {
  55956. this._colorGradients.splice(index, 1);
  55957. break;
  55958. }
  55959. index++;
  55960. }
  55961. return this;
  55962. };
  55963. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  55964. u = Math.abs(u) * 0.5 + 0.5;
  55965. v = Math.abs(v) * 0.5 + 0.5;
  55966. var wrappedU = ((u * width) % width) | 0;
  55967. var wrappedV = ((v * height) % height) | 0;
  55968. var position = (wrappedU + wrappedV * width) * 4;
  55969. return pixels[position] / 255;
  55970. };
  55971. ParticleSystem.prototype._reset = function () {
  55972. this._resetEffect();
  55973. };
  55974. ParticleSystem.prototype._resetEffect = function () {
  55975. if (this._vertexBuffer) {
  55976. this._vertexBuffer.dispose();
  55977. this._vertexBuffer = null;
  55978. }
  55979. if (this._spriteBuffer) {
  55980. this._spriteBuffer.dispose();
  55981. this._spriteBuffer = null;
  55982. }
  55983. this._createVertexBuffers();
  55984. };
  55985. ParticleSystem.prototype._createVertexBuffers = function () {
  55986. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55987. if (this._isAnimationSheetEnabled) {
  55988. this._vertexBufferSize += 1;
  55989. }
  55990. if (!this._isBillboardBased) {
  55991. this._vertexBufferSize += 3;
  55992. }
  55993. var engine = this._scene.getEngine();
  55994. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55995. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55996. var dataOffset = 0;
  55997. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55998. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55999. dataOffset += 3;
  56000. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56001. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56002. dataOffset += 4;
  56003. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56004. this._vertexBuffers["angle"] = options;
  56005. dataOffset += 1;
  56006. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56007. this._vertexBuffers["size"] = size;
  56008. dataOffset += 2;
  56009. if (this._isAnimationSheetEnabled) {
  56010. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56011. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56012. dataOffset += 1;
  56013. }
  56014. if (!this._isBillboardBased) {
  56015. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56016. this._vertexBuffers["direction"] = directionBuffer;
  56017. dataOffset += 3;
  56018. }
  56019. var offsets;
  56020. if (this._useInstancing) {
  56021. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56022. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56023. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56024. }
  56025. else {
  56026. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56027. dataOffset += 2;
  56028. }
  56029. this._vertexBuffers["offset"] = offsets;
  56030. };
  56031. ParticleSystem.prototype._createIndexBuffer = function () {
  56032. if (this._useInstancing) {
  56033. return;
  56034. }
  56035. var indices = [];
  56036. var index = 0;
  56037. for (var count = 0; count < this._capacity; count++) {
  56038. indices.push(index);
  56039. indices.push(index + 1);
  56040. indices.push(index + 2);
  56041. indices.push(index);
  56042. indices.push(index + 2);
  56043. indices.push(index + 3);
  56044. index += 4;
  56045. }
  56046. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56047. };
  56048. /**
  56049. * Gets the maximum number of particles active at the same time.
  56050. * @returns The max number of active particles.
  56051. */
  56052. ParticleSystem.prototype.getCapacity = function () {
  56053. return this._capacity;
  56054. };
  56055. /**
  56056. * Gets whether there are still active particles in the system.
  56057. * @returns True if it is alive, otherwise false.
  56058. */
  56059. ParticleSystem.prototype.isAlive = function () {
  56060. return this._alive;
  56061. };
  56062. /**
  56063. * Gets whether the system has been started.
  56064. * @returns True if it has been started, otherwise false.
  56065. */
  56066. ParticleSystem.prototype.isStarted = function () {
  56067. return this._started;
  56068. };
  56069. /**
  56070. * Starts the particle system and begins to emit
  56071. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56072. */
  56073. ParticleSystem.prototype.start = function (delay) {
  56074. var _this = this;
  56075. if (delay === void 0) { delay = 0; }
  56076. if (delay) {
  56077. setTimeout(function () {
  56078. _this.start(0);
  56079. }, delay);
  56080. return;
  56081. }
  56082. this._started = true;
  56083. this._stopped = false;
  56084. this._actualFrame = 0;
  56085. if (this.subEmitters && this.subEmitters.length != 0) {
  56086. this.activeSubSystems = new Array();
  56087. }
  56088. if (this.preWarmCycles) {
  56089. for (var index = 0; index < this.preWarmCycles; index++) {
  56090. this.animate(true);
  56091. }
  56092. }
  56093. };
  56094. /**
  56095. * Stops the particle system.
  56096. * @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.
  56097. */
  56098. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56099. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56100. this._stopped = true;
  56101. if (stopSubEmitters) {
  56102. this._stopSubEmitters();
  56103. }
  56104. };
  56105. // animation sheet
  56106. /**
  56107. * Remove all active particles
  56108. */
  56109. ParticleSystem.prototype.reset = function () {
  56110. this._stockParticles = [];
  56111. this._particles = [];
  56112. };
  56113. /**
  56114. * @hidden (for internal use only)
  56115. */
  56116. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56117. var offset = index * this._vertexBufferSize;
  56118. this._vertexData[offset++] = particle.position.x;
  56119. this._vertexData[offset++] = particle.position.y;
  56120. this._vertexData[offset++] = particle.position.z;
  56121. this._vertexData[offset++] = particle.color.r;
  56122. this._vertexData[offset++] = particle.color.g;
  56123. this._vertexData[offset++] = particle.color.b;
  56124. this._vertexData[offset++] = particle.color.a;
  56125. this._vertexData[offset++] = particle.angle;
  56126. this._vertexData[offset++] = particle.scale.x * particle.size;
  56127. this._vertexData[offset++] = particle.scale.y * particle.size;
  56128. if (this._isAnimationSheetEnabled) {
  56129. this._vertexData[offset++] = particle.cellIndex;
  56130. }
  56131. if (!this._isBillboardBased) {
  56132. if (particle._initialDirection) {
  56133. this._vertexData[offset++] = particle._initialDirection.x;
  56134. this._vertexData[offset++] = particle._initialDirection.y;
  56135. this._vertexData[offset++] = particle._initialDirection.z;
  56136. }
  56137. else {
  56138. this._vertexData[offset++] = particle.direction.x;
  56139. this._vertexData[offset++] = particle.direction.y;
  56140. this._vertexData[offset++] = particle.direction.z;
  56141. }
  56142. }
  56143. if (!this._useInstancing) {
  56144. if (this._isAnimationSheetEnabled) {
  56145. if (offsetX === 0)
  56146. offsetX = this._epsilon;
  56147. else if (offsetX === 1)
  56148. offsetX = 1 - this._epsilon;
  56149. if (offsetY === 0)
  56150. offsetY = this._epsilon;
  56151. else if (offsetY === 1)
  56152. offsetY = 1 - this._epsilon;
  56153. }
  56154. this._vertexData[offset++] = offsetX;
  56155. this._vertexData[offset++] = offsetY;
  56156. }
  56157. };
  56158. ParticleSystem.prototype._stopSubEmitters = function () {
  56159. if (!this.activeSubSystems) {
  56160. return;
  56161. }
  56162. this.activeSubSystems.forEach(function (subSystem) {
  56163. subSystem.stop(true);
  56164. });
  56165. this.activeSubSystems = new Array();
  56166. };
  56167. ParticleSystem.prototype._removeFromRoot = function () {
  56168. if (!this._rootParticleSystem) {
  56169. return;
  56170. }
  56171. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56172. if (index !== -1) {
  56173. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56174. }
  56175. };
  56176. // End of sub system methods
  56177. ParticleSystem.prototype._update = function (newParticles) {
  56178. // Update current
  56179. this._alive = this._particles.length > 0;
  56180. if (this.emitter.position) {
  56181. var emitterMesh = this.emitter;
  56182. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56183. }
  56184. else {
  56185. var emitterPosition = this.emitter;
  56186. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56187. }
  56188. this.updateFunction(this._particles);
  56189. // Add new ones
  56190. var particle;
  56191. var _loop_2 = function () {
  56192. if (this_1._particles.length === this_1._capacity) {
  56193. return "break";
  56194. }
  56195. particle = this_1._createParticle();
  56196. this_1._particles.push(particle);
  56197. // Emitter
  56198. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56199. if (this_1.startPositionFunction) {
  56200. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56201. }
  56202. else {
  56203. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56204. }
  56205. if (this_1.startDirectionFunction) {
  56206. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56207. }
  56208. else {
  56209. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56210. }
  56211. if (emitPower === 0) {
  56212. if (!particle._initialDirection) {
  56213. particle._initialDirection = particle.direction.clone();
  56214. }
  56215. else {
  56216. particle._initialDirection.copyFrom(particle.direction);
  56217. }
  56218. }
  56219. else {
  56220. particle._initialDirection = null;
  56221. }
  56222. particle.direction.scaleInPlace(emitPower);
  56223. // Life time
  56224. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56225. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56226. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56227. var factorGradient1 = currentGradient;
  56228. var factorGradient2 = nextGradient;
  56229. var lifeTime1 = factorGradient1.getFactor();
  56230. var lifeTime2 = factorGradient2.getFactor();
  56231. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56232. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56233. });
  56234. }
  56235. else {
  56236. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56237. }
  56238. // Size
  56239. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56240. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56241. }
  56242. else {
  56243. particle._currentSizeGradient = this_1._sizeGradients[0];
  56244. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56245. particle.size = particle._currentSize1;
  56246. if (this_1._sizeGradients.length > 1) {
  56247. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56248. }
  56249. else {
  56250. particle._currentSize2 = particle._currentSize1;
  56251. }
  56252. }
  56253. // Size and scale
  56254. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56255. // Angle
  56256. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56257. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56258. }
  56259. else {
  56260. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56261. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56262. particle._currentAngularSpeed1 = particle.angularSpeed;
  56263. if (this_1._angularSpeedGradients.length > 1) {
  56264. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56265. }
  56266. else {
  56267. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56268. }
  56269. }
  56270. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56271. // Velocity
  56272. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56273. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56274. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56275. if (this_1._velocityGradients.length > 1) {
  56276. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56277. }
  56278. else {
  56279. particle._currentVelocity2 = particle._currentVelocity1;
  56280. }
  56281. }
  56282. // Color
  56283. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56284. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56285. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56286. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56287. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56288. }
  56289. else {
  56290. particle._currentColorGradient = this_1._colorGradients[0];
  56291. particle._currentColorGradient.getColorToRef(particle.color);
  56292. particle._currentColor1.copyFrom(particle.color);
  56293. if (this_1._colorGradients.length > 1) {
  56294. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56295. }
  56296. else {
  56297. particle._currentColor2.copyFrom(particle.color);
  56298. }
  56299. }
  56300. // Sheet
  56301. if (this_1._isAnimationSheetEnabled) {
  56302. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56303. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56304. }
  56305. };
  56306. var this_1 = this, step;
  56307. for (var index = 0; index < newParticles; index++) {
  56308. var state_1 = _loop_2();
  56309. if (state_1 === "break")
  56310. break;
  56311. }
  56312. };
  56313. /** @hidden */
  56314. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56315. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56316. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56317. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56318. if (isAnimationSheetEnabled) {
  56319. attributeNamesOrOptions.push("cellIndex");
  56320. }
  56321. if (!isBillboardBased) {
  56322. attributeNamesOrOptions.push("direction");
  56323. }
  56324. return attributeNamesOrOptions;
  56325. };
  56326. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56327. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56328. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  56329. if (isAnimationSheetEnabled) {
  56330. effectCreationOption.push("particlesInfos");
  56331. }
  56332. return effectCreationOption;
  56333. };
  56334. ParticleSystem.prototype._getEffect = function () {
  56335. if (this._customEffect) {
  56336. return this._customEffect;
  56337. }
  56338. ;
  56339. var defines = [];
  56340. if (this._scene.clipPlane) {
  56341. defines.push("#define CLIPPLANE");
  56342. }
  56343. if (this._isAnimationSheetEnabled) {
  56344. defines.push("#define ANIMATESHEET");
  56345. }
  56346. if (this._isBillboardBased) {
  56347. defines.push("#define BILLBOARD");
  56348. switch (this.billboardMode) {
  56349. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56350. defines.push("#define BILLBOARDY");
  56351. break;
  56352. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56353. default:
  56354. break;
  56355. }
  56356. }
  56357. // Effect
  56358. var join = defines.join("\n");
  56359. if (this._cachedDefines !== join) {
  56360. this._cachedDefines = join;
  56361. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56362. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56363. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56364. }
  56365. return this._effect;
  56366. };
  56367. /**
  56368. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56369. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56370. */
  56371. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56372. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56373. if (!this._started)
  56374. return;
  56375. if (!preWarmOnly) {
  56376. var effect = this._getEffect();
  56377. // Check
  56378. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56379. return;
  56380. if (this._currentRenderId === this._scene.getRenderId()) {
  56381. return;
  56382. }
  56383. this._currentRenderId = this._scene.getRenderId();
  56384. }
  56385. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56386. // determine the number of particles we need to create
  56387. var newParticles;
  56388. if (this.manualEmitCount > -1) {
  56389. newParticles = this.manualEmitCount;
  56390. this._newPartsExcess = 0;
  56391. this.manualEmitCount = 0;
  56392. }
  56393. else {
  56394. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56395. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56396. }
  56397. if (this._newPartsExcess > 1.0) {
  56398. newParticles += this._newPartsExcess >> 0;
  56399. this._newPartsExcess -= this._newPartsExcess >> 0;
  56400. }
  56401. this._alive = false;
  56402. if (!this._stopped) {
  56403. this._actualFrame += this._scaledUpdateSpeed;
  56404. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56405. this.stop();
  56406. }
  56407. else {
  56408. newParticles = 0;
  56409. }
  56410. this._update(newParticles);
  56411. // Stopped?
  56412. if (this._stopped) {
  56413. if (!this._alive) {
  56414. this._started = false;
  56415. if (this.onAnimationEnd) {
  56416. this.onAnimationEnd();
  56417. }
  56418. if (this.disposeOnStop) {
  56419. this._scene._toBeDisposed.push(this);
  56420. }
  56421. }
  56422. }
  56423. if (!preWarmOnly) {
  56424. // Update VBO
  56425. var offset = 0;
  56426. for (var index = 0; index < this._particles.length; index++) {
  56427. var particle = this._particles[index];
  56428. this._appendParticleVertices(offset, particle);
  56429. offset += this._useInstancing ? 1 : 4;
  56430. }
  56431. if (this._vertexBuffer) {
  56432. this._vertexBuffer.update(this._vertexData);
  56433. }
  56434. }
  56435. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56436. this.stop();
  56437. }
  56438. };
  56439. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56440. this._appendParticleVertex(offset++, particle, 0, 0);
  56441. if (!this._useInstancing) {
  56442. this._appendParticleVertex(offset++, particle, 1, 0);
  56443. this._appendParticleVertex(offset++, particle, 1, 1);
  56444. this._appendParticleVertex(offset++, particle, 0, 1);
  56445. }
  56446. };
  56447. /**
  56448. * Rebuilds the particle system.
  56449. */
  56450. ParticleSystem.prototype.rebuild = function () {
  56451. this._createIndexBuffer();
  56452. if (this._vertexBuffer) {
  56453. this._vertexBuffer._rebuild();
  56454. }
  56455. };
  56456. /**
  56457. * Is this system ready to be used/rendered
  56458. * @return true if the system is ready
  56459. */
  56460. ParticleSystem.prototype.isReady = function () {
  56461. var effect = this._getEffect();
  56462. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56463. return false;
  56464. }
  56465. return true;
  56466. };
  56467. /**
  56468. * Renders the particle system in its current state.
  56469. * @returns the current number of particles
  56470. */
  56471. ParticleSystem.prototype.render = function () {
  56472. var effect = this._getEffect();
  56473. // Check
  56474. if (!this.isReady() || !this._particles.length) {
  56475. return 0;
  56476. }
  56477. var engine = this._scene.getEngine();
  56478. // Render
  56479. engine.enableEffect(effect);
  56480. engine.setState(false);
  56481. var viewMatrix = this._scene.getViewMatrix();
  56482. effect.setTexture("diffuseSampler", this.particleTexture);
  56483. effect.setMatrix("view", viewMatrix);
  56484. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56485. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56486. var baseSize = this.particleTexture.getBaseSize();
  56487. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56488. }
  56489. effect.setVector2("translationPivot", this.translationPivot);
  56490. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56491. if (this._isBillboardBased) {
  56492. var camera = this._scene.activeCamera;
  56493. effect.setVector3("eyePosition", camera.globalPosition);
  56494. }
  56495. if (this._scene.clipPlane) {
  56496. var clipPlane = this._scene.clipPlane;
  56497. var invView = viewMatrix.clone();
  56498. invView.invert();
  56499. effect.setMatrix("invView", invView);
  56500. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56501. }
  56502. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56503. // Draw order
  56504. switch (this.blendMode) {
  56505. case ParticleSystem.BLENDMODE_ADD:
  56506. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56507. break;
  56508. case ParticleSystem.BLENDMODE_ONEONE:
  56509. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56510. break;
  56511. case ParticleSystem.BLENDMODE_STANDARD:
  56512. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56513. break;
  56514. }
  56515. if (this.forceDepthWrite) {
  56516. engine.setDepthWrite(true);
  56517. }
  56518. if (this._useInstancing) {
  56519. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56520. engine.unbindInstanceAttributes();
  56521. }
  56522. else {
  56523. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56524. }
  56525. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56526. return this._particles.length;
  56527. };
  56528. /**
  56529. * Disposes the particle system and free the associated resources
  56530. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56531. */
  56532. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56533. if (disposeTexture === void 0) { disposeTexture = true; }
  56534. if (this._vertexBuffer) {
  56535. this._vertexBuffer.dispose();
  56536. this._vertexBuffer = null;
  56537. }
  56538. if (this._spriteBuffer) {
  56539. this._spriteBuffer.dispose();
  56540. this._spriteBuffer = null;
  56541. }
  56542. if (this._indexBuffer) {
  56543. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56544. this._indexBuffer = null;
  56545. }
  56546. if (disposeTexture && this.particleTexture) {
  56547. this.particleTexture.dispose();
  56548. this.particleTexture = null;
  56549. }
  56550. if (disposeTexture && this.noiseTexture) {
  56551. this.noiseTexture.dispose();
  56552. this.noiseTexture = null;
  56553. }
  56554. this._removeFromRoot();
  56555. // Remove from scene
  56556. var index = this._scene.particleSystems.indexOf(this);
  56557. if (index > -1) {
  56558. this._scene.particleSystems.splice(index, 1);
  56559. }
  56560. // Callback
  56561. this.onDisposeObservable.notifyObservers(this);
  56562. this.onDisposeObservable.clear();
  56563. };
  56564. // Clone
  56565. /**
  56566. * Clones the particle system.
  56567. * @param name The name of the cloned object
  56568. * @param newEmitter The new emitter to use
  56569. * @returns the cloned particle system
  56570. */
  56571. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56572. var custom = null;
  56573. var program = null;
  56574. if (this.customShader != null) {
  56575. program = this.customShader;
  56576. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56577. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56578. }
  56579. else if (this._customEffect) {
  56580. custom = this._customEffect;
  56581. }
  56582. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56583. result.customShader = program;
  56584. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56585. if (newEmitter === undefined) {
  56586. newEmitter = this.emitter;
  56587. }
  56588. result.emitter = newEmitter;
  56589. if (this.particleTexture) {
  56590. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56591. }
  56592. if (!this.preventAutoStart) {
  56593. result.start();
  56594. }
  56595. return result;
  56596. };
  56597. /**
  56598. * Serializes the particle system to a JSON object.
  56599. * @returns the JSON object
  56600. */
  56601. ParticleSystem.prototype.serialize = function () {
  56602. var serializationObject = {};
  56603. ParticleSystem._Serialize(serializationObject, this);
  56604. serializationObject.textureMask = this.textureMask.asArray();
  56605. serializationObject.customShader = this.customShader;
  56606. serializationObject.preventAutoStart = this.preventAutoStart;
  56607. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56608. return serializationObject;
  56609. };
  56610. /** @hidden */
  56611. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56612. serializationObject.name = particleSystem.name;
  56613. serializationObject.id = particleSystem.id;
  56614. serializationObject.capacity = particleSystem.getCapacity();
  56615. // Emitter
  56616. if (particleSystem.emitter.position) {
  56617. var emitterMesh = particleSystem.emitter;
  56618. serializationObject.emitterId = emitterMesh.id;
  56619. }
  56620. else {
  56621. var emitterPosition = particleSystem.emitter;
  56622. serializationObject.emitter = emitterPosition.asArray();
  56623. }
  56624. // Emitter
  56625. if (particleSystem.particleEmitterType) {
  56626. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56627. }
  56628. if (particleSystem.particleTexture) {
  56629. serializationObject.textureName = particleSystem.particleTexture.name;
  56630. }
  56631. // Animations
  56632. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56633. // Particle system
  56634. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56635. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56636. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56637. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56638. serializationObject.minSize = particleSystem.minSize;
  56639. serializationObject.maxSize = particleSystem.maxSize;
  56640. serializationObject.minScaleX = particleSystem.minScaleX;
  56641. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56642. serializationObject.minScaleY = particleSystem.minScaleY;
  56643. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56644. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56645. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56646. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56647. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56648. serializationObject.emitRate = particleSystem.emitRate;
  56649. serializationObject.gravity = particleSystem.gravity.asArray();
  56650. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56651. serializationObject.color1 = particleSystem.color1.asArray();
  56652. serializationObject.color2 = particleSystem.color2.asArray();
  56653. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56654. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56655. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56656. serializationObject.blendMode = particleSystem.blendMode;
  56657. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56658. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56659. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56660. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56661. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56662. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56663. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56664. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56665. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56666. var colorGradients = particleSystem.getColorGradients();
  56667. if (colorGradients) {
  56668. serializationObject.colorGradients = [];
  56669. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56670. var colorGradient = colorGradients_1[_i];
  56671. var serializedGradient = {
  56672. gradient: colorGradient.gradient,
  56673. color1: colorGradient.color1.asArray()
  56674. };
  56675. if (colorGradient.color2) {
  56676. serializedGradient.color2 = colorGradient.color2.asArray();
  56677. }
  56678. serializationObject.colorGradients.push(serializedGradient);
  56679. }
  56680. }
  56681. var sizeGradients = particleSystem.getSizeGradients();
  56682. if (sizeGradients) {
  56683. serializationObject.sizeGradients = [];
  56684. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56685. var sizeGradient = sizeGradients_1[_a];
  56686. var serializedGradient = {
  56687. gradient: sizeGradient.gradient,
  56688. factor1: sizeGradient.factor1
  56689. };
  56690. if (sizeGradient.factor2 !== undefined) {
  56691. serializedGradient.factor2 = sizeGradient.factor2;
  56692. }
  56693. serializationObject.sizeGradients.push(serializedGradient);
  56694. }
  56695. }
  56696. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56697. if (angularSpeedGradients) {
  56698. serializationObject.angularSpeedGradients = [];
  56699. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56700. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56701. var serializedGradient = {
  56702. gradient: angularSpeedGradient.gradient,
  56703. factor1: angularSpeedGradient.factor1
  56704. };
  56705. if (angularSpeedGradient.factor2 !== undefined) {
  56706. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56707. }
  56708. serializationObject.angularSpeedGradients.push(serializedGradient);
  56709. }
  56710. }
  56711. var velocityGradients = particleSystem.getVelocityGradients();
  56712. if (velocityGradients) {
  56713. serializationObject.velocityGradients = [];
  56714. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56715. var velocityGradient = velocityGradients_1[_c];
  56716. var serializedGradient = {
  56717. gradient: velocityGradient.gradient,
  56718. factor1: velocityGradient.factor1
  56719. };
  56720. if (velocityGradient.factor2 !== undefined) {
  56721. serializedGradient.factor2 = velocityGradient.factor2;
  56722. }
  56723. serializationObject.velocityGradients.push(serializedGradient);
  56724. }
  56725. }
  56726. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  56727. var noiseTexture = particleSystem.noiseTexture;
  56728. serializationObject.noiseTexture = noiseTexture.serialize();
  56729. }
  56730. };
  56731. /** @hidden */
  56732. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56733. // Texture
  56734. if (parsedParticleSystem.textureName) {
  56735. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56736. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56737. }
  56738. // Emitter
  56739. if (parsedParticleSystem.emitterId === undefined) {
  56740. particleSystem.emitter = BABYLON.Vector3.Zero();
  56741. }
  56742. else if (parsedParticleSystem.emitterId) {
  56743. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56744. }
  56745. else {
  56746. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56747. }
  56748. // Misc.
  56749. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56750. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56751. }
  56752. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56753. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56754. }
  56755. // Animations
  56756. if (parsedParticleSystem.animations) {
  56757. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56758. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56759. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56760. }
  56761. }
  56762. if (parsedParticleSystem.autoAnimate) {
  56763. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56764. }
  56765. // Particle system
  56766. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56767. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56768. particleSystem.minSize = parsedParticleSystem.minSize;
  56769. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56770. if (parsedParticleSystem.minScaleX) {
  56771. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56772. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56773. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56774. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56775. }
  56776. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56777. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56778. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56779. }
  56780. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56781. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56782. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56783. }
  56784. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56785. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56786. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56787. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56788. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56789. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56790. if (parsedParticleSystem.noiseStrength) {
  56791. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  56792. }
  56793. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56794. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56795. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56796. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56797. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56798. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56799. if (parsedParticleSystem.colorGradients) {
  56800. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56801. var colorGradient = _a[_i];
  56802. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56803. }
  56804. }
  56805. if (parsedParticleSystem.sizeGradients) {
  56806. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56807. var sizeGradient = _c[_b];
  56808. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56809. }
  56810. }
  56811. if (parsedParticleSystem.angularSpeedGradients) {
  56812. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56813. var angularSpeedGradient = _e[_d];
  56814. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56815. }
  56816. }
  56817. if (parsedParticleSystem.velocityGradients) {
  56818. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56819. var velocityGradient = _g[_f];
  56820. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56821. }
  56822. }
  56823. if (parsedParticleSystem.noiseTexture) {
  56824. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  56825. }
  56826. // Emitter
  56827. var emitterType;
  56828. if (parsedParticleSystem.particleEmitterType) {
  56829. switch (parsedParticleSystem.particleEmitterType.type) {
  56830. case "SphereParticleEmitter":
  56831. emitterType = new BABYLON.SphereParticleEmitter();
  56832. break;
  56833. case "SphereDirectedParticleEmitter":
  56834. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56835. break;
  56836. case "ConeEmitter":
  56837. case "ConeParticleEmitter":
  56838. emitterType = new BABYLON.ConeParticleEmitter();
  56839. break;
  56840. case "BoxEmitter":
  56841. case "BoxParticleEmitter":
  56842. default:
  56843. emitterType = new BABYLON.BoxParticleEmitter();
  56844. break;
  56845. }
  56846. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56847. }
  56848. else {
  56849. emitterType = new BABYLON.BoxParticleEmitter();
  56850. emitterType.parse(parsedParticleSystem);
  56851. }
  56852. particleSystem.particleEmitterType = emitterType;
  56853. // Animation sheet
  56854. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56855. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56856. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56857. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56858. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56859. };
  56860. /**
  56861. * Parses a JSON object to create a particle system.
  56862. * @param parsedParticleSystem The JSON object to parse
  56863. * @param scene The scene to create the particle system in
  56864. * @param rootUrl The root url to use to load external dependencies like texture
  56865. * @returns the Parsed particle system
  56866. */
  56867. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56868. var name = parsedParticleSystem.name;
  56869. var custom = null;
  56870. var program = null;
  56871. if (parsedParticleSystem.customShader) {
  56872. program = parsedParticleSystem.customShader;
  56873. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56874. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56875. }
  56876. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56877. particleSystem.customShader = program;
  56878. if (parsedParticleSystem.id) {
  56879. particleSystem.id = parsedParticleSystem.id;
  56880. }
  56881. // Auto start
  56882. if (parsedParticleSystem.preventAutoStart) {
  56883. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56884. }
  56885. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56886. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56887. if (!particleSystem.preventAutoStart) {
  56888. particleSystem.start();
  56889. }
  56890. return particleSystem;
  56891. };
  56892. return ParticleSystem;
  56893. }(BABYLON.BaseParticleSystem));
  56894. BABYLON.ParticleSystem = ParticleSystem;
  56895. })(BABYLON || (BABYLON = {}));
  56896. //# sourceMappingURL=babylon.particleSystem.js.map
  56897. var BABYLON;
  56898. (function (BABYLON) {
  56899. /**
  56900. * Particle emitter emitting particles from the inside of a box.
  56901. * It emits the particles randomly between 2 given directions.
  56902. */
  56903. var BoxParticleEmitter = /** @class */ (function () {
  56904. /**
  56905. * Creates a new instance BoxParticleEmitter
  56906. */
  56907. function BoxParticleEmitter() {
  56908. /**
  56909. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56910. */
  56911. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56912. /**
  56913. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56914. */
  56915. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56916. /**
  56917. * 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.
  56918. */
  56919. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56920. /**
  56921. * 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.
  56922. */
  56923. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56924. }
  56925. /**
  56926. * Called by the particle System when the direction is computed for the created particle.
  56927. * @param worldMatrix is the world matrix of the particle system
  56928. * @param directionToUpdate is the direction vector to update with the result
  56929. * @param particle is the particle we are computed the direction for
  56930. */
  56931. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56932. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56933. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56934. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56935. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56936. };
  56937. /**
  56938. * Called by the particle System when the position is computed for the created particle.
  56939. * @param worldMatrix is the world matrix of the particle system
  56940. * @param positionToUpdate is the position vector to update with the result
  56941. * @param particle is the particle we are computed the position for
  56942. */
  56943. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56944. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56945. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56946. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56947. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56948. };
  56949. /**
  56950. * Clones the current emitter and returns a copy of it
  56951. * @returns the new emitter
  56952. */
  56953. BoxParticleEmitter.prototype.clone = function () {
  56954. var newOne = new BoxParticleEmitter();
  56955. BABYLON.Tools.DeepCopy(this, newOne);
  56956. return newOne;
  56957. };
  56958. /**
  56959. * Called by the GPUParticleSystem to setup the update shader
  56960. * @param effect defines the update shader
  56961. */
  56962. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56963. effect.setVector3("direction1", this.direction1);
  56964. effect.setVector3("direction2", this.direction2);
  56965. effect.setVector3("minEmitBox", this.minEmitBox);
  56966. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56967. };
  56968. /**
  56969. * Returns a string to use to update the GPU particles update shader
  56970. * @returns a string containng the defines string
  56971. */
  56972. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56973. return "#define BOXEMITTER";
  56974. };
  56975. /**
  56976. * Returns the string "BoxParticleEmitter"
  56977. * @returns a string containing the class name
  56978. */
  56979. BoxParticleEmitter.prototype.getClassName = function () {
  56980. return "BoxParticleEmitter";
  56981. };
  56982. /**
  56983. * Serializes the particle system to a JSON object.
  56984. * @returns the JSON object
  56985. */
  56986. BoxParticleEmitter.prototype.serialize = function () {
  56987. var serializationObject = {};
  56988. serializationObject.type = this.getClassName();
  56989. serializationObject.direction1 = this.direction1.asArray();
  56990. serializationObject.direction2 = this.direction2.asArray();
  56991. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56992. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56993. return serializationObject;
  56994. };
  56995. /**
  56996. * Parse properties from a JSON object
  56997. * @param serializationObject defines the JSON object
  56998. */
  56999. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57000. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57001. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57002. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57003. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57004. };
  57005. return BoxParticleEmitter;
  57006. }());
  57007. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57008. })(BABYLON || (BABYLON = {}));
  57009. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57010. var BABYLON;
  57011. (function (BABYLON) {
  57012. /**
  57013. * Particle emitter emitting particles from the inside of a cone.
  57014. * It emits the particles alongside the cone volume from the base to the particle.
  57015. * The emission direction might be randomized.
  57016. */
  57017. var ConeParticleEmitter = /** @class */ (function () {
  57018. /**
  57019. * Creates a new instance ConeParticleEmitter
  57020. * @param radius the radius of the emission cone (1 by default)
  57021. * @param angles the cone base angle (PI by default)
  57022. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57023. */
  57024. function ConeParticleEmitter(radius, angle,
  57025. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57026. directionRandomizer) {
  57027. if (radius === void 0) { radius = 1; }
  57028. if (angle === void 0) { angle = Math.PI; }
  57029. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57030. this.directionRandomizer = directionRandomizer;
  57031. /**
  57032. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57033. */
  57034. this.radiusRange = 1;
  57035. /**
  57036. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57037. */
  57038. this.heightRange = 1;
  57039. /**
  57040. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57041. */
  57042. this.emitFromSpawnPointOnly = false;
  57043. this.angle = angle;
  57044. this.radius = radius;
  57045. }
  57046. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57047. /**
  57048. * Gets or sets the radius of the emission cone
  57049. */
  57050. get: function () {
  57051. return this._radius;
  57052. },
  57053. set: function (value) {
  57054. this._radius = value;
  57055. this._buildHeight();
  57056. },
  57057. enumerable: true,
  57058. configurable: true
  57059. });
  57060. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57061. /**
  57062. * Gets or sets the angle of the emission cone
  57063. */
  57064. get: function () {
  57065. return this._angle;
  57066. },
  57067. set: function (value) {
  57068. this._angle = value;
  57069. this._buildHeight();
  57070. },
  57071. enumerable: true,
  57072. configurable: true
  57073. });
  57074. ConeParticleEmitter.prototype._buildHeight = function () {
  57075. if (this._angle !== 0) {
  57076. this._height = this._radius / Math.tan(this._angle / 2);
  57077. }
  57078. else {
  57079. this._height = 1;
  57080. }
  57081. };
  57082. /**
  57083. * Called by the particle System when the direction is computed for the created particle.
  57084. * @param worldMatrix is the world matrix of the particle system
  57085. * @param directionToUpdate is the direction vector to update with the result
  57086. * @param particle is the particle we are computed the direction for
  57087. */
  57088. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57089. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  57090. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  57091. }
  57092. else {
  57093. // measure the direction Vector from the emitter to the particle.
  57094. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57095. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57096. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57097. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57098. direction.x += randX;
  57099. direction.y += randY;
  57100. direction.z += randZ;
  57101. direction.normalize();
  57102. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57103. }
  57104. };
  57105. /**
  57106. * Called by the particle System when the position is computed for the created particle.
  57107. * @param worldMatrix is the world matrix of the particle system
  57108. * @param positionToUpdate is the position vector to update with the result
  57109. * @param particle is the particle we are computed the position for
  57110. */
  57111. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57112. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57113. var h;
  57114. if (!this.emitFromSpawnPointOnly) {
  57115. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  57116. // Better distribution in a cone at normal angles.
  57117. h = 1 - h * h;
  57118. }
  57119. else {
  57120. h = 0.0001;
  57121. }
  57122. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  57123. radius = radius * h;
  57124. var randX = radius * Math.sin(s);
  57125. var randZ = radius * Math.cos(s);
  57126. var randY = h * this._height;
  57127. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57128. };
  57129. /**
  57130. * Clones the current emitter and returns a copy of it
  57131. * @returns the new emitter
  57132. */
  57133. ConeParticleEmitter.prototype.clone = function () {
  57134. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57135. BABYLON.Tools.DeepCopy(this, newOne);
  57136. return newOne;
  57137. };
  57138. /**
  57139. * Called by the GPUParticleSystem to setup the update shader
  57140. * @param effect defines the update shader
  57141. */
  57142. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57143. effect.setFloat2("radius", this._radius, this.radiusRange);
  57144. effect.setFloat("coneAngle", this._angle);
  57145. effect.setFloat2("height", this._height, this.heightRange);
  57146. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57147. };
  57148. /**
  57149. * Returns a string to use to update the GPU particles update shader
  57150. * @returns a string containng the defines string
  57151. */
  57152. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57153. var defines = "#define CONEEMITTER";
  57154. if (this.emitFromSpawnPointOnly) {
  57155. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57156. }
  57157. return defines;
  57158. };
  57159. /**
  57160. * Returns the string "ConeParticleEmitter"
  57161. * @returns a string containing the class name
  57162. */
  57163. ConeParticleEmitter.prototype.getClassName = function () {
  57164. return "ConeParticleEmitter";
  57165. };
  57166. /**
  57167. * Serializes the particle system to a JSON object.
  57168. * @returns the JSON object
  57169. */
  57170. ConeParticleEmitter.prototype.serialize = function () {
  57171. var serializationObject = {};
  57172. serializationObject.type = this.getClassName();
  57173. serializationObject.radius = this._radius;
  57174. serializationObject.angle = this._angle;
  57175. serializationObject.directionRandomizer = this.directionRandomizer;
  57176. return serializationObject;
  57177. };
  57178. /**
  57179. * Parse properties from a JSON object
  57180. * @param serializationObject defines the JSON object
  57181. */
  57182. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57183. this.radius = serializationObject.radius;
  57184. this.angle = serializationObject.angle;
  57185. this.directionRandomizer = serializationObject.directionRandomizer;
  57186. };
  57187. return ConeParticleEmitter;
  57188. }());
  57189. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57190. })(BABYLON || (BABYLON = {}));
  57191. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57192. var BABYLON;
  57193. (function (BABYLON) {
  57194. /**
  57195. * Particle emitter emitting particles from the inside of a sphere.
  57196. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57197. */
  57198. var SphereParticleEmitter = /** @class */ (function () {
  57199. /**
  57200. * Creates a new instance SphereParticleEmitter
  57201. * @param radius the radius of the emission sphere (1 by default)
  57202. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57203. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57204. */
  57205. function SphereParticleEmitter(
  57206. /**
  57207. * The radius of the emission sphere.
  57208. */
  57209. radius,
  57210. /**
  57211. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57212. */
  57213. radiusRange,
  57214. /**
  57215. * How much to randomize the particle direction [0-1].
  57216. */
  57217. directionRandomizer) {
  57218. if (radius === void 0) { radius = 1; }
  57219. if (radiusRange === void 0) { radiusRange = 1; }
  57220. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57221. this.radius = radius;
  57222. this.radiusRange = radiusRange;
  57223. this.directionRandomizer = directionRandomizer;
  57224. }
  57225. /**
  57226. * Called by the particle System when the direction is computed for the created particle.
  57227. * @param worldMatrix is the world matrix of the particle system
  57228. * @param directionToUpdate is the direction vector to update with the result
  57229. * @param particle is the particle we are computed the direction for
  57230. */
  57231. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57232. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57233. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57234. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57235. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57236. direction.x += randX;
  57237. direction.y += randY;
  57238. direction.z += randZ;
  57239. direction.normalize();
  57240. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57241. };
  57242. /**
  57243. * Called by the particle System when the position is computed for the created particle.
  57244. * @param worldMatrix is the world matrix of the particle system
  57245. * @param positionToUpdate is the position vector to update with the result
  57246. * @param particle is the particle we are computed the position for
  57247. */
  57248. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57249. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57250. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57251. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57252. var theta = Math.acos(2 * v - 1);
  57253. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57254. var randY = randRadius * Math.cos(theta);
  57255. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  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. SphereParticleEmitter.prototype.clone = function () {
  57263. var newOne = new SphereParticleEmitter(this.radius, 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. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57272. effect.setFloat("radius", this.radius);
  57273. effect.setFloat("radiusRange", this.radiusRange);
  57274. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57275. };
  57276. /**
  57277. * Returns a string to use to update the GPU particles update shader
  57278. * @returns a string containng the defines string
  57279. */
  57280. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57281. return "#define SPHEREEMITTER";
  57282. };
  57283. /**
  57284. * Returns the string "SphereParticleEmitter"
  57285. * @returns a string containing the class name
  57286. */
  57287. SphereParticleEmitter.prototype.getClassName = function () {
  57288. return "SphereParticleEmitter";
  57289. };
  57290. /**
  57291. * Serializes the particle system to a JSON object.
  57292. * @returns the JSON object
  57293. */
  57294. SphereParticleEmitter.prototype.serialize = function () {
  57295. var serializationObject = {};
  57296. serializationObject.type = this.getClassName();
  57297. serializationObject.radius = this.radius;
  57298. serializationObject.radiusRange = this.radiusRange;
  57299. serializationObject.directionRandomizer = this.directionRandomizer;
  57300. return serializationObject;
  57301. };
  57302. /**
  57303. * Parse properties from a JSON object
  57304. * @param serializationObject defines the JSON object
  57305. */
  57306. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57307. this.radius = serializationObject.radius;
  57308. this.radiusRange = serializationObject.radiusRange;
  57309. this.directionRandomizer = serializationObject.directionRandomizer;
  57310. };
  57311. return SphereParticleEmitter;
  57312. }());
  57313. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57314. /**
  57315. * Particle emitter emitting particles from the inside of a sphere.
  57316. * It emits the particles randomly between two vectors.
  57317. */
  57318. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57319. __extends(SphereDirectedParticleEmitter, _super);
  57320. /**
  57321. * Creates a new instance SphereDirectedParticleEmitter
  57322. * @param radius the radius of the emission sphere (1 by default)
  57323. * @param direction1 the min limit of the emission direction (up vector by default)
  57324. * @param direction2 the max limit of the emission direction (up vector by default)
  57325. */
  57326. function SphereDirectedParticleEmitter(radius,
  57327. /**
  57328. * The min limit of the emission direction.
  57329. */
  57330. direction1,
  57331. /**
  57332. * The max limit of the emission direction.
  57333. */
  57334. direction2) {
  57335. if (radius === void 0) { radius = 1; }
  57336. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57337. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57338. var _this = _super.call(this, radius) || this;
  57339. _this.direction1 = direction1;
  57340. _this.direction2 = direction2;
  57341. return _this;
  57342. }
  57343. /**
  57344. * Called by the particle System when the direction is computed for the created particle.
  57345. * @param worldMatrix is the world matrix of the particle system
  57346. * @param directionToUpdate is the direction vector to update with the result
  57347. * @param particle is the particle we are computed the direction for
  57348. */
  57349. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57350. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57351. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57352. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57353. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57354. };
  57355. /**
  57356. * Clones the current emitter and returns a copy of it
  57357. * @returns the new emitter
  57358. */
  57359. SphereDirectedParticleEmitter.prototype.clone = function () {
  57360. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57361. BABYLON.Tools.DeepCopy(this, newOne);
  57362. return newOne;
  57363. };
  57364. /**
  57365. * Called by the GPUParticleSystem to setup the update shader
  57366. * @param effect defines the update shader
  57367. */
  57368. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57369. effect.setFloat("radius", this.radius);
  57370. effect.setFloat("radiusRange", this.radiusRange);
  57371. effect.setVector3("direction1", this.direction1);
  57372. effect.setVector3("direction2", this.direction2);
  57373. };
  57374. /**
  57375. * Returns a string to use to update the GPU particles update shader
  57376. * @returns a string containng the defines string
  57377. */
  57378. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57379. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57380. };
  57381. /**
  57382. * Returns the string "SphereDirectedParticleEmitter"
  57383. * @returns a string containing the class name
  57384. */
  57385. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57386. return "SphereDirectedParticleEmitter";
  57387. };
  57388. /**
  57389. * Serializes the particle system to a JSON object.
  57390. * @returns the JSON object
  57391. */
  57392. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57393. var serializationObject = _super.prototype.serialize.call(this);
  57394. serializationObject.direction1 = this.direction1.asArray();
  57395. serializationObject.direction2 = this.direction2.asArray();
  57396. return serializationObject;
  57397. };
  57398. /**
  57399. * Parse properties from a JSON object
  57400. * @param serializationObject defines the JSON object
  57401. */
  57402. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57403. _super.prototype.parse.call(this, serializationObject);
  57404. this.direction1.copyFrom(serializationObject.direction1);
  57405. this.direction2.copyFrom(serializationObject.direction2);
  57406. };
  57407. return SphereDirectedParticleEmitter;
  57408. }(SphereParticleEmitter));
  57409. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57410. })(BABYLON || (BABYLON = {}));
  57411. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57412. var BABYLON;
  57413. (function (BABYLON) {
  57414. /**
  57415. * Particle emitter emitting particles from the inside of a hemisphere.
  57416. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  57417. */
  57418. var HemisphericParticleEmitter = /** @class */ (function () {
  57419. /**
  57420. * Creates a new instance HemisphericParticleEmitter
  57421. * @param radius the radius of the emission hemisphere (1 by default)
  57422. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57423. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57424. */
  57425. function HemisphericParticleEmitter(
  57426. /**
  57427. * The radius of the emission hemisphere.
  57428. */
  57429. radius,
  57430. /**
  57431. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57432. */
  57433. radiusRange,
  57434. /**
  57435. * How much to randomize the particle direction [0-1].
  57436. */
  57437. directionRandomizer) {
  57438. if (radius === void 0) { radius = 1; }
  57439. if (radiusRange === void 0) { radiusRange = 1; }
  57440. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57441. this.radius = radius;
  57442. this.radiusRange = radiusRange;
  57443. this.directionRandomizer = directionRandomizer;
  57444. }
  57445. /**
  57446. * Called by the particle System when the direction is computed for the created particle.
  57447. * @param worldMatrix is the world matrix of the particle system
  57448. * @param directionToUpdate is the direction vector to update with the result
  57449. * @param particle is the particle we are computed the direction for
  57450. */
  57451. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57452. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57453. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57454. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57455. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57456. direction.x += randX;
  57457. direction.y += randY;
  57458. direction.z += randZ;
  57459. direction.normalize();
  57460. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57461. };
  57462. /**
  57463. * Called by the particle System when the position is computed for the created particle.
  57464. * @param worldMatrix is the world matrix of the particle system
  57465. * @param positionToUpdate is the position vector to update with the result
  57466. * @param particle is the particle we are computed the position for
  57467. */
  57468. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57469. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57470. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57471. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57472. var theta = Math.acos(2 * v - 1);
  57473. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57474. var randY = randRadius * Math.cos(theta);
  57475. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57476. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  57477. };
  57478. /**
  57479. * Clones the current emitter and returns a copy of it
  57480. * @returns the new emitter
  57481. */
  57482. HemisphericParticleEmitter.prototype.clone = function () {
  57483. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  57484. BABYLON.Tools.DeepCopy(this, newOne);
  57485. return newOne;
  57486. };
  57487. /**
  57488. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57489. * @param effect defines the update shader
  57490. */
  57491. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  57492. effect.setFloat("radius", this.radius);
  57493. effect.setFloat("radiusRange", this.radiusRange);
  57494. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57495. };
  57496. /**
  57497. * Returns a string to use to update the GPU particles update shader
  57498. * @returns a string containng the defines string
  57499. */
  57500. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  57501. return "#define HEMISPHERICEMITTER";
  57502. };
  57503. /**
  57504. * Returns the string "HemisphericParticleEmitter"
  57505. * @returns a string containing the class name
  57506. */
  57507. HemisphericParticleEmitter.prototype.getClassName = function () {
  57508. return "HemisphericParticleEmitter";
  57509. };
  57510. /**
  57511. * Serializes the particle system to a JSON object.
  57512. * @returns the JSON object
  57513. */
  57514. HemisphericParticleEmitter.prototype.serialize = function () {
  57515. var serializationObject = {};
  57516. serializationObject.type = this.getClassName();
  57517. serializationObject.radius = this.radius;
  57518. serializationObject.radiusRange = this.radiusRange;
  57519. serializationObject.directionRandomizer = this.directionRandomizer;
  57520. return serializationObject;
  57521. };
  57522. /**
  57523. * Parse properties from a JSON object
  57524. * @param serializationObject defines the JSON object
  57525. */
  57526. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  57527. this.radius = serializationObject.radius;
  57528. this.radiusRange = serializationObject.radiusRange;
  57529. this.directionRandomizer = serializationObject.directionRandomizer;
  57530. };
  57531. return HemisphericParticleEmitter;
  57532. }());
  57533. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  57534. })(BABYLON || (BABYLON = {}));
  57535. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  57536. var BABYLON;
  57537. (function (BABYLON) {
  57538. /**
  57539. * Particle emitter emitting particles from a point.
  57540. * It emits the particles randomly between 2 given directions.
  57541. */
  57542. var PointParticleEmitter = /** @class */ (function () {
  57543. /**
  57544. * Creates a new instance PointParticleEmitter
  57545. */
  57546. function PointParticleEmitter() {
  57547. /**
  57548. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57549. */
  57550. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57551. /**
  57552. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57553. */
  57554. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57555. }
  57556. /**
  57557. * Called by the particle System when the direction is computed for the created particle.
  57558. * @param worldMatrix is the world matrix of the particle system
  57559. * @param directionToUpdate is the direction vector to update with the result
  57560. * @param particle is the particle we are computed the direction for
  57561. */
  57562. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57563. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57564. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57565. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57566. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57567. };
  57568. /**
  57569. * Called by the particle System when the position is computed for the created particle.
  57570. * @param worldMatrix is the world matrix of the particle system
  57571. * @param positionToUpdate is the position vector to update with the result
  57572. * @param particle is the particle we are computed the position for
  57573. */
  57574. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57575. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  57576. };
  57577. /**
  57578. * Clones the current emitter and returns a copy of it
  57579. * @returns the new emitter
  57580. */
  57581. PointParticleEmitter.prototype.clone = function () {
  57582. var newOne = new PointParticleEmitter();
  57583. BABYLON.Tools.DeepCopy(this, newOne);
  57584. return newOne;
  57585. };
  57586. /**
  57587. * Called by the GPUParticleSystem to setup the update shader
  57588. * @param effect defines the update shader
  57589. */
  57590. PointParticleEmitter.prototype.applyToShader = function (effect) {
  57591. effect.setVector3("direction1", this.direction1);
  57592. effect.setVector3("direction2", this.direction2);
  57593. };
  57594. /**
  57595. * Returns a string to use to update the GPU particles update shader
  57596. * @returns a string containng the defines string
  57597. */
  57598. PointParticleEmitter.prototype.getEffectDefines = function () {
  57599. return "#define POINTEMITTER";
  57600. };
  57601. /**
  57602. * Returns the string "PointParticleEmitter"
  57603. * @returns a string containing the class name
  57604. */
  57605. PointParticleEmitter.prototype.getClassName = function () {
  57606. return "PointParticleEmitter";
  57607. };
  57608. /**
  57609. * Serializes the particle system to a JSON object.
  57610. * @returns the JSON object
  57611. */
  57612. PointParticleEmitter.prototype.serialize = function () {
  57613. var serializationObject = {};
  57614. serializationObject.type = this.getClassName();
  57615. serializationObject.direction1 = this.direction1.asArray();
  57616. serializationObject.direction2 = this.direction2.asArray();
  57617. return serializationObject;
  57618. };
  57619. /**
  57620. * Parse properties from a JSON object
  57621. * @param serializationObject defines the JSON object
  57622. */
  57623. PointParticleEmitter.prototype.parse = function (serializationObject) {
  57624. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57625. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57626. };
  57627. return PointParticleEmitter;
  57628. }());
  57629. BABYLON.PointParticleEmitter = PointParticleEmitter;
  57630. })(BABYLON || (BABYLON = {}));
  57631. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  57632. var BABYLON;
  57633. (function (BABYLON) {
  57634. // Adds the parsers to the scene parsers.
  57635. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57636. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57637. if (!individualParser) {
  57638. return;
  57639. }
  57640. // Particles Systems
  57641. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57642. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57643. var parsedParticleSystem = parsedData.particleSystems[index];
  57644. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57645. }
  57646. }
  57647. });
  57648. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57649. if (parsedParticleSystem.activeParticleCount) {
  57650. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57651. return ps;
  57652. }
  57653. else {
  57654. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57655. return ps;
  57656. }
  57657. });
  57658. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57659. if (uniformsNames === void 0) { uniformsNames = []; }
  57660. if (samplers === void 0) { samplers = []; }
  57661. if (defines === void 0) { defines = ""; }
  57662. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57663. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57664. if (defines.indexOf(" BILLBOARD") === -1) {
  57665. defines += "\n#define BILLBOARD\n";
  57666. }
  57667. if (samplers.indexOf("diffuseSampler") === -1) {
  57668. samplers.push("diffuseSampler");
  57669. }
  57670. return this.createEffect({
  57671. vertex: "particles",
  57672. fragmentElement: fragmentName
  57673. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57674. };
  57675. })(BABYLON || (BABYLON = {}));
  57676. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57677. var BABYLON;
  57678. (function (BABYLON) {
  57679. var ShaderMaterial = /** @class */ (function (_super) {
  57680. __extends(ShaderMaterial, _super);
  57681. function ShaderMaterial(name, scene, shaderPath, options) {
  57682. var _this = _super.call(this, name, scene) || this;
  57683. _this._textures = {};
  57684. _this._textureArrays = {};
  57685. _this._floats = {};
  57686. _this._ints = {};
  57687. _this._floatsArrays = {};
  57688. _this._colors3 = {};
  57689. _this._colors3Arrays = {};
  57690. _this._colors4 = {};
  57691. _this._vectors2 = {};
  57692. _this._vectors3 = {};
  57693. _this._vectors4 = {};
  57694. _this._matrices = {};
  57695. _this._matrices3x3 = {};
  57696. _this._matrices2x2 = {};
  57697. _this._vectors2Arrays = {};
  57698. _this._vectors3Arrays = {};
  57699. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57700. _this._shaderPath = shaderPath;
  57701. options.needAlphaBlending = options.needAlphaBlending || false;
  57702. options.needAlphaTesting = options.needAlphaTesting || false;
  57703. options.attributes = options.attributes || ["position", "normal", "uv"];
  57704. options.uniforms = options.uniforms || ["worldViewProjection"];
  57705. options.uniformBuffers = options.uniformBuffers || [];
  57706. options.samplers = options.samplers || [];
  57707. options.defines = options.defines || [];
  57708. _this._options = options;
  57709. return _this;
  57710. }
  57711. ShaderMaterial.prototype.getClassName = function () {
  57712. return "ShaderMaterial";
  57713. };
  57714. ShaderMaterial.prototype.needAlphaBlending = function () {
  57715. return this._options.needAlphaBlending;
  57716. };
  57717. ShaderMaterial.prototype.needAlphaTesting = function () {
  57718. return this._options.needAlphaTesting;
  57719. };
  57720. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57721. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57722. this._options.uniforms.push(uniformName);
  57723. }
  57724. };
  57725. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57726. if (this._options.samplers.indexOf(name) === -1) {
  57727. this._options.samplers.push(name);
  57728. }
  57729. this._textures[name] = texture;
  57730. return this;
  57731. };
  57732. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57733. if (this._options.samplers.indexOf(name) === -1) {
  57734. this._options.samplers.push(name);
  57735. }
  57736. this._checkUniform(name);
  57737. this._textureArrays[name] = textures;
  57738. return this;
  57739. };
  57740. ShaderMaterial.prototype.setFloat = function (name, value) {
  57741. this._checkUniform(name);
  57742. this._floats[name] = value;
  57743. return this;
  57744. };
  57745. ShaderMaterial.prototype.setInt = function (name, value) {
  57746. this._checkUniform(name);
  57747. this._ints[name] = value;
  57748. return this;
  57749. };
  57750. ShaderMaterial.prototype.setFloats = function (name, value) {
  57751. this._checkUniform(name);
  57752. this._floatsArrays[name] = value;
  57753. return this;
  57754. };
  57755. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57756. this._checkUniform(name);
  57757. this._colors3[name] = value;
  57758. return this;
  57759. };
  57760. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57761. this._checkUniform(name);
  57762. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57763. color.toArray(arr, arr.length);
  57764. return arr;
  57765. }, []);
  57766. return this;
  57767. };
  57768. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57769. this._checkUniform(name);
  57770. this._colors4[name] = value;
  57771. return this;
  57772. };
  57773. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57774. this._checkUniform(name);
  57775. this._vectors2[name] = value;
  57776. return this;
  57777. };
  57778. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57779. this._checkUniform(name);
  57780. this._vectors3[name] = value;
  57781. return this;
  57782. };
  57783. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57784. this._checkUniform(name);
  57785. this._vectors4[name] = value;
  57786. return this;
  57787. };
  57788. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57789. this._checkUniform(name);
  57790. this._matrices[name] = value;
  57791. return this;
  57792. };
  57793. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57794. this._checkUniform(name);
  57795. this._matrices3x3[name] = value;
  57796. return this;
  57797. };
  57798. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57799. this._checkUniform(name);
  57800. this._matrices2x2[name] = value;
  57801. return this;
  57802. };
  57803. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57804. this._checkUniform(name);
  57805. this._vectors2Arrays[name] = value;
  57806. return this;
  57807. };
  57808. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57809. this._checkUniform(name);
  57810. this._vectors3Arrays[name] = value;
  57811. return this;
  57812. };
  57813. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57814. if (!mesh) {
  57815. return true;
  57816. }
  57817. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57818. return false;
  57819. }
  57820. return false;
  57821. };
  57822. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57823. var scene = this.getScene();
  57824. var engine = scene.getEngine();
  57825. if (!this.checkReadyOnEveryCall) {
  57826. if (this._renderId === scene.getRenderId()) {
  57827. if (this._checkCache(scene, mesh, useInstances)) {
  57828. return true;
  57829. }
  57830. }
  57831. }
  57832. // Instances
  57833. var defines = [];
  57834. var attribs = [];
  57835. var fallbacks = new BABYLON.EffectFallbacks();
  57836. if (useInstances) {
  57837. defines.push("#define INSTANCES");
  57838. }
  57839. for (var index = 0; index < this._options.defines.length; index++) {
  57840. defines.push(this._options.defines[index]);
  57841. }
  57842. for (var index = 0; index < this._options.attributes.length; index++) {
  57843. attribs.push(this._options.attributes[index]);
  57844. }
  57845. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57846. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57847. defines.push("#define VERTEXCOLOR");
  57848. }
  57849. // Bones
  57850. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57851. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57852. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57853. if (mesh.numBoneInfluencers > 4) {
  57854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57856. }
  57857. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57858. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57859. fallbacks.addCPUSkinningFallback(0, mesh);
  57860. if (this._options.uniforms.indexOf("mBones") === -1) {
  57861. this._options.uniforms.push("mBones");
  57862. }
  57863. }
  57864. else {
  57865. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57866. }
  57867. // Textures
  57868. for (var name in this._textures) {
  57869. if (!this._textures[name].isReady()) {
  57870. return false;
  57871. }
  57872. }
  57873. // Alpha test
  57874. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57875. defines.push("#define ALPHATEST");
  57876. }
  57877. var previousEffect = this._effect;
  57878. var join = defines.join("\n");
  57879. this._effect = engine.createEffect(this._shaderPath, {
  57880. attributes: attribs,
  57881. uniformsNames: this._options.uniforms,
  57882. uniformBuffersNames: this._options.uniformBuffers,
  57883. samplers: this._options.samplers,
  57884. defines: join,
  57885. fallbacks: fallbacks,
  57886. onCompiled: this.onCompiled,
  57887. onError: this.onError
  57888. }, engine);
  57889. if (!this._effect.isReady()) {
  57890. return false;
  57891. }
  57892. if (previousEffect !== this._effect) {
  57893. scene.resetCachedMaterial();
  57894. }
  57895. this._renderId = scene.getRenderId();
  57896. return true;
  57897. };
  57898. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57899. var scene = this.getScene();
  57900. if (!this._effect) {
  57901. return;
  57902. }
  57903. if (this._options.uniforms.indexOf("world") !== -1) {
  57904. this._effect.setMatrix("world", world);
  57905. }
  57906. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57907. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57908. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57909. }
  57910. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57911. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57912. }
  57913. };
  57914. ShaderMaterial.prototype.bind = function (world, mesh) {
  57915. // Std values
  57916. this.bindOnlyWorldMatrix(world);
  57917. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57918. if (this._options.uniforms.indexOf("view") !== -1) {
  57919. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57920. }
  57921. if (this._options.uniforms.indexOf("projection") !== -1) {
  57922. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57923. }
  57924. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57925. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57926. }
  57927. // Bones
  57928. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57929. var name;
  57930. // Texture
  57931. for (name in this._textures) {
  57932. this._effect.setTexture(name, this._textures[name]);
  57933. }
  57934. // Texture arrays
  57935. for (name in this._textureArrays) {
  57936. this._effect.setTextureArray(name, this._textureArrays[name]);
  57937. }
  57938. // Int
  57939. for (name in this._ints) {
  57940. this._effect.setInt(name, this._ints[name]);
  57941. }
  57942. // Float
  57943. for (name in this._floats) {
  57944. this._effect.setFloat(name, this._floats[name]);
  57945. }
  57946. // Floats
  57947. for (name in this._floatsArrays) {
  57948. this._effect.setArray(name, this._floatsArrays[name]);
  57949. }
  57950. // Color3
  57951. for (name in this._colors3) {
  57952. this._effect.setColor3(name, this._colors3[name]);
  57953. }
  57954. for (name in this._colors3Arrays) {
  57955. this._effect.setArray3(name, this._colors3Arrays[name]);
  57956. }
  57957. // Color4
  57958. for (name in this._colors4) {
  57959. var color = this._colors4[name];
  57960. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57961. }
  57962. // Vector2
  57963. for (name in this._vectors2) {
  57964. this._effect.setVector2(name, this._vectors2[name]);
  57965. }
  57966. // Vector3
  57967. for (name in this._vectors3) {
  57968. this._effect.setVector3(name, this._vectors3[name]);
  57969. }
  57970. // Vector4
  57971. for (name in this._vectors4) {
  57972. this._effect.setVector4(name, this._vectors4[name]);
  57973. }
  57974. // Matrix
  57975. for (name in this._matrices) {
  57976. this._effect.setMatrix(name, this._matrices[name]);
  57977. }
  57978. // Matrix 3x3
  57979. for (name in this._matrices3x3) {
  57980. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57981. }
  57982. // Matrix 2x2
  57983. for (name in this._matrices2x2) {
  57984. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57985. }
  57986. // Vector2Array
  57987. for (name in this._vectors2Arrays) {
  57988. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57989. }
  57990. // Vector3Array
  57991. for (name in this._vectors3Arrays) {
  57992. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57993. }
  57994. }
  57995. this._afterBind(mesh);
  57996. };
  57997. ShaderMaterial.prototype.getActiveTextures = function () {
  57998. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57999. for (var name in this._textures) {
  58000. activeTextures.push(this._textures[name]);
  58001. }
  58002. for (var name in this._textureArrays) {
  58003. var array = this._textureArrays[name];
  58004. for (var index = 0; index < array.length; index++) {
  58005. activeTextures.push(array[index]);
  58006. }
  58007. }
  58008. return activeTextures;
  58009. };
  58010. ShaderMaterial.prototype.hasTexture = function (texture) {
  58011. if (_super.prototype.hasTexture.call(this, texture)) {
  58012. return true;
  58013. }
  58014. for (var name in this._textures) {
  58015. if (this._textures[name] === texture) {
  58016. return true;
  58017. }
  58018. }
  58019. for (var name in this._textureArrays) {
  58020. var array = this._textureArrays[name];
  58021. for (var index = 0; index < array.length; index++) {
  58022. if (array[index] === texture) {
  58023. return true;
  58024. }
  58025. }
  58026. }
  58027. return false;
  58028. };
  58029. ShaderMaterial.prototype.clone = function (name) {
  58030. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58031. return newShaderMaterial;
  58032. };
  58033. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58034. if (forceDisposeTextures) {
  58035. var name;
  58036. for (name in this._textures) {
  58037. this._textures[name].dispose();
  58038. }
  58039. for (name in this._textureArrays) {
  58040. var array = this._textureArrays[name];
  58041. for (var index = 0; index < array.length; index++) {
  58042. array[index].dispose();
  58043. }
  58044. }
  58045. }
  58046. this._textures = {};
  58047. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58048. };
  58049. ShaderMaterial.prototype.serialize = function () {
  58050. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58051. serializationObject.customType = "BABYLON.ShaderMaterial";
  58052. serializationObject.options = this._options;
  58053. serializationObject.shaderPath = this._shaderPath;
  58054. var name;
  58055. // Texture
  58056. serializationObject.textures = {};
  58057. for (name in this._textures) {
  58058. serializationObject.textures[name] = this._textures[name].serialize();
  58059. }
  58060. // Texture arrays
  58061. serializationObject.textureArrays = {};
  58062. for (name in this._textureArrays) {
  58063. serializationObject.textureArrays[name] = [];
  58064. var array = this._textureArrays[name];
  58065. for (var index = 0; index < array.length; index++) {
  58066. serializationObject.textureArrays[name].push(array[index].serialize());
  58067. }
  58068. }
  58069. // Float
  58070. serializationObject.floats = {};
  58071. for (name in this._floats) {
  58072. serializationObject.floats[name] = this._floats[name];
  58073. }
  58074. // Float s
  58075. serializationObject.FloatArrays = {};
  58076. for (name in this._floatsArrays) {
  58077. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58078. }
  58079. // Color3
  58080. serializationObject.colors3 = {};
  58081. for (name in this._colors3) {
  58082. serializationObject.colors3[name] = this._colors3[name].asArray();
  58083. }
  58084. // Color3 array
  58085. serializationObject.colors3Arrays = {};
  58086. for (name in this._colors3Arrays) {
  58087. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58088. }
  58089. // Color4
  58090. serializationObject.colors4 = {};
  58091. for (name in this._colors4) {
  58092. serializationObject.colors4[name] = this._colors4[name].asArray();
  58093. }
  58094. // Vector2
  58095. serializationObject.vectors2 = {};
  58096. for (name in this._vectors2) {
  58097. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58098. }
  58099. // Vector3
  58100. serializationObject.vectors3 = {};
  58101. for (name in this._vectors3) {
  58102. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58103. }
  58104. // Vector4
  58105. serializationObject.vectors4 = {};
  58106. for (name in this._vectors4) {
  58107. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58108. }
  58109. // Matrix
  58110. serializationObject.matrices = {};
  58111. for (name in this._matrices) {
  58112. serializationObject.matrices[name] = this._matrices[name].asArray();
  58113. }
  58114. // Matrix 3x3
  58115. serializationObject.matrices3x3 = {};
  58116. for (name in this._matrices3x3) {
  58117. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58118. }
  58119. // Matrix 2x2
  58120. serializationObject.matrices2x2 = {};
  58121. for (name in this._matrices2x2) {
  58122. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58123. }
  58124. // Vector2Array
  58125. serializationObject.vectors2Arrays = {};
  58126. for (name in this._vectors2Arrays) {
  58127. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58128. }
  58129. // Vector3Array
  58130. serializationObject.vectors3Arrays = {};
  58131. for (name in this._vectors3Arrays) {
  58132. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58133. }
  58134. return serializationObject;
  58135. };
  58136. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58137. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58138. var name;
  58139. // Texture
  58140. for (name in source.textures) {
  58141. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58142. }
  58143. // Texture arrays
  58144. for (name in source.textureArrays) {
  58145. var array = source.textureArrays[name];
  58146. var textureArray = new Array();
  58147. for (var index = 0; index < array.length; index++) {
  58148. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58149. }
  58150. material.setTextureArray(name, textureArray);
  58151. }
  58152. // Float
  58153. for (name in source.floats) {
  58154. material.setFloat(name, source.floats[name]);
  58155. }
  58156. // Float s
  58157. for (name in source.floatsArrays) {
  58158. material.setFloats(name, source.floatsArrays[name]);
  58159. }
  58160. // Color3
  58161. for (name in source.colors3) {
  58162. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58163. }
  58164. // Color3 arrays
  58165. for (name in source.colors3Arrays) {
  58166. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58167. if (i % 3 === 0) {
  58168. arr.push([num]);
  58169. }
  58170. else {
  58171. arr[arr.length - 1].push(num);
  58172. }
  58173. return arr;
  58174. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58175. material.setColor3Array(name, colors);
  58176. }
  58177. // Color4
  58178. for (name in source.colors4) {
  58179. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58180. }
  58181. // Vector2
  58182. for (name in source.vectors2) {
  58183. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58184. }
  58185. // Vector3
  58186. for (name in source.vectors3) {
  58187. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58188. }
  58189. // Vector4
  58190. for (name in source.vectors4) {
  58191. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58192. }
  58193. // Matrix
  58194. for (name in source.matrices) {
  58195. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58196. }
  58197. // Matrix 3x3
  58198. for (name in source.matrices3x3) {
  58199. material.setMatrix3x3(name, source.matrices3x3[name]);
  58200. }
  58201. // Matrix 2x2
  58202. for (name in source.matrices2x2) {
  58203. material.setMatrix2x2(name, source.matrices2x2[name]);
  58204. }
  58205. // Vector2Array
  58206. for (name in source.vectors2Arrays) {
  58207. material.setArray2(name, source.vectors2Arrays[name]);
  58208. }
  58209. // Vector3Array
  58210. for (name in source.vectors3Arrays) {
  58211. material.setArray3(name, source.vectors3Arrays[name]);
  58212. }
  58213. return material;
  58214. };
  58215. return ShaderMaterial;
  58216. }(BABYLON.Material));
  58217. BABYLON.ShaderMaterial = ShaderMaterial;
  58218. })(BABYLON || (BABYLON = {}));
  58219. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58220. var BABYLON;
  58221. (function (BABYLON) {
  58222. var GroundMesh = /** @class */ (function (_super) {
  58223. __extends(GroundMesh, _super);
  58224. function GroundMesh(name, scene) {
  58225. var _this = _super.call(this, name, scene) || this;
  58226. _this.generateOctree = false;
  58227. return _this;
  58228. }
  58229. GroundMesh.prototype.getClassName = function () {
  58230. return "GroundMesh";
  58231. };
  58232. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58233. get: function () {
  58234. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58235. },
  58236. enumerable: true,
  58237. configurable: true
  58238. });
  58239. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58240. get: function () {
  58241. return this._subdivisionsX;
  58242. },
  58243. enumerable: true,
  58244. configurable: true
  58245. });
  58246. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58247. get: function () {
  58248. return this._subdivisionsY;
  58249. },
  58250. enumerable: true,
  58251. configurable: true
  58252. });
  58253. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58254. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58255. this._subdivisionsX = chunksCount;
  58256. this._subdivisionsY = chunksCount;
  58257. this.subdivide(chunksCount);
  58258. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58259. };
  58260. /**
  58261. * Returns a height (y) value in the Worl system :
  58262. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58263. * Returns the ground y position if (x, z) are outside the ground surface.
  58264. */
  58265. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58266. var world = this.getWorldMatrix();
  58267. var invMat = BABYLON.Tmp.Matrix[5];
  58268. world.invertToRef(invMat);
  58269. var tmpVect = BABYLON.Tmp.Vector3[8];
  58270. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58271. x = tmpVect.x;
  58272. z = tmpVect.z;
  58273. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58274. return this.position.y;
  58275. }
  58276. if (!this._heightQuads || this._heightQuads.length == 0) {
  58277. this._initHeightQuads();
  58278. this._computeHeightQuads();
  58279. }
  58280. var facet = this._getFacetAt(x, z);
  58281. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58282. // return y in the World system
  58283. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58284. return tmpVect.y;
  58285. };
  58286. /**
  58287. * Returns a normalized vector (Vector3) orthogonal to the ground
  58288. * at the ground coordinates (x, z) expressed in the World system.
  58289. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58290. */
  58291. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58292. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58293. this.getNormalAtCoordinatesToRef(x, z, normal);
  58294. return normal;
  58295. };
  58296. /**
  58297. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58298. * at the ground coordinates (x, z) expressed in the World system.
  58299. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58300. * Returns the GroundMesh.
  58301. */
  58302. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58303. var world = this.getWorldMatrix();
  58304. var tmpMat = BABYLON.Tmp.Matrix[5];
  58305. world.invertToRef(tmpMat);
  58306. var tmpVect = BABYLON.Tmp.Vector3[8];
  58307. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58308. x = tmpVect.x;
  58309. z = tmpVect.z;
  58310. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58311. return this;
  58312. }
  58313. if (!this._heightQuads || this._heightQuads.length == 0) {
  58314. this._initHeightQuads();
  58315. this._computeHeightQuads();
  58316. }
  58317. var facet = this._getFacetAt(x, z);
  58318. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58319. return this;
  58320. };
  58321. /**
  58322. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58323. * if the ground has been updated.
  58324. * This can be used in the render loop.
  58325. * Returns the GroundMesh.
  58326. */
  58327. GroundMesh.prototype.updateCoordinateHeights = function () {
  58328. if (!this._heightQuads || this._heightQuads.length == 0) {
  58329. this._initHeightQuads();
  58330. }
  58331. this._computeHeightQuads();
  58332. return this;
  58333. };
  58334. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58335. GroundMesh.prototype._getFacetAt = function (x, z) {
  58336. // retrieve col and row from x, z coordinates in the ground local system
  58337. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58338. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58339. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58340. var facet;
  58341. if (z < quad.slope.x * x + quad.slope.y) {
  58342. facet = quad.facet1;
  58343. }
  58344. else {
  58345. facet = quad.facet2;
  58346. }
  58347. return facet;
  58348. };
  58349. // Creates and populates the heightMap array with "facet" elements :
  58350. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58351. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58352. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58353. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58354. // Returns the GroundMesh.
  58355. GroundMesh.prototype._initHeightQuads = function () {
  58356. var subdivisionsX = this._subdivisionsX;
  58357. var subdivisionsY = this._subdivisionsY;
  58358. this._heightQuads = new Array();
  58359. for (var row = 0; row < subdivisionsY; row++) {
  58360. for (var col = 0; col < subdivisionsX; col++) {
  58361. 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) };
  58362. this._heightQuads[row * subdivisionsX + col] = quad;
  58363. }
  58364. }
  58365. return this;
  58366. };
  58367. // Compute each quad element values and update the the heightMap array :
  58368. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58369. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58370. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58371. // Returns the GroundMesh.
  58372. GroundMesh.prototype._computeHeightQuads = function () {
  58373. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58374. if (!positions) {
  58375. return this;
  58376. }
  58377. var v1 = BABYLON.Tmp.Vector3[3];
  58378. var v2 = BABYLON.Tmp.Vector3[2];
  58379. var v3 = BABYLON.Tmp.Vector3[1];
  58380. var v4 = BABYLON.Tmp.Vector3[0];
  58381. var v1v2 = BABYLON.Tmp.Vector3[4];
  58382. var v1v3 = BABYLON.Tmp.Vector3[5];
  58383. var v1v4 = BABYLON.Tmp.Vector3[6];
  58384. var norm1 = BABYLON.Tmp.Vector3[7];
  58385. var norm2 = BABYLON.Tmp.Vector3[8];
  58386. var i = 0;
  58387. var j = 0;
  58388. var k = 0;
  58389. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58390. var h = 0;
  58391. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58392. var d2 = 0;
  58393. var subdivisionsX = this._subdivisionsX;
  58394. var subdivisionsY = this._subdivisionsY;
  58395. for (var row = 0; row < subdivisionsY; row++) {
  58396. for (var col = 0; col < subdivisionsX; col++) {
  58397. i = col * 3;
  58398. j = row * (subdivisionsX + 1) * 3;
  58399. k = (row + 1) * (subdivisionsX + 1) * 3;
  58400. v1.x = positions[j + i];
  58401. v1.y = positions[j + i + 1];
  58402. v1.z = positions[j + i + 2];
  58403. v2.x = positions[j + i + 3];
  58404. v2.y = positions[j + i + 4];
  58405. v2.z = positions[j + i + 5];
  58406. v3.x = positions[k + i];
  58407. v3.y = positions[k + i + 1];
  58408. v3.z = positions[k + i + 2];
  58409. v4.x = positions[k + i + 3];
  58410. v4.y = positions[k + i + 4];
  58411. v4.z = positions[k + i + 5];
  58412. // 2D slope V1V4
  58413. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58414. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58415. // facet equations :
  58416. // we compute each facet normal vector
  58417. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58418. // we compute the value d by applying the equation to v1 which belongs to the plane
  58419. // then we store the facet equation in a Vector4
  58420. v2.subtractToRef(v1, v1v2);
  58421. v3.subtractToRef(v1, v1v3);
  58422. v4.subtractToRef(v1, v1v4);
  58423. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58424. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58425. norm1.normalize();
  58426. norm2.normalize();
  58427. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58428. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58429. var quad = this._heightQuads[row * subdivisionsX + col];
  58430. quad.slope.copyFromFloats(cd, h);
  58431. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58432. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58433. }
  58434. }
  58435. return this;
  58436. };
  58437. GroundMesh.prototype.serialize = function (serializationObject) {
  58438. _super.prototype.serialize.call(this, serializationObject);
  58439. serializationObject.subdivisionsX = this._subdivisionsX;
  58440. serializationObject.subdivisionsY = this._subdivisionsY;
  58441. serializationObject.minX = this._minX;
  58442. serializationObject.maxX = this._maxX;
  58443. serializationObject.minZ = this._minZ;
  58444. serializationObject.maxZ = this._maxZ;
  58445. serializationObject.width = this._width;
  58446. serializationObject.height = this._height;
  58447. };
  58448. GroundMesh.Parse = function (parsedMesh, scene) {
  58449. var result = new GroundMesh(parsedMesh.name, scene);
  58450. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58451. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58452. result._minX = parsedMesh.minX;
  58453. result._maxX = parsedMesh.maxX;
  58454. result._minZ = parsedMesh.minZ;
  58455. result._maxZ = parsedMesh.maxZ;
  58456. result._width = parsedMesh.width;
  58457. result._height = parsedMesh.height;
  58458. return result;
  58459. };
  58460. return GroundMesh;
  58461. }(BABYLON.Mesh));
  58462. BABYLON.GroundMesh = GroundMesh;
  58463. })(BABYLON || (BABYLON = {}));
  58464. //# sourceMappingURL=babylon.groundMesh.js.map
  58465. var BABYLON;
  58466. (function (BABYLON) {
  58467. /**
  58468. * Creates an instance based on a source mesh.
  58469. */
  58470. var InstancedMesh = /** @class */ (function (_super) {
  58471. __extends(InstancedMesh, _super);
  58472. function InstancedMesh(name, source) {
  58473. var _this = _super.call(this, name, source.getScene()) || this;
  58474. source.instances.push(_this);
  58475. _this._sourceMesh = source;
  58476. _this.position.copyFrom(source.position);
  58477. _this.rotation.copyFrom(source.rotation);
  58478. _this.scaling.copyFrom(source.scaling);
  58479. if (source.rotationQuaternion) {
  58480. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58481. }
  58482. _this.infiniteDistance = source.infiniteDistance;
  58483. _this.setPivotMatrix(source.getPivotMatrix());
  58484. _this.refreshBoundingInfo();
  58485. _this._syncSubMeshes();
  58486. return _this;
  58487. }
  58488. /**
  58489. * Returns the string "InstancedMesh".
  58490. */
  58491. InstancedMesh.prototype.getClassName = function () {
  58492. return "InstancedMesh";
  58493. };
  58494. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58495. // Methods
  58496. get: function () {
  58497. return this._sourceMesh.receiveShadows;
  58498. },
  58499. enumerable: true,
  58500. configurable: true
  58501. });
  58502. Object.defineProperty(InstancedMesh.prototype, "material", {
  58503. get: function () {
  58504. return this._sourceMesh.material;
  58505. },
  58506. enumerable: true,
  58507. configurable: true
  58508. });
  58509. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58510. get: function () {
  58511. return this._sourceMesh.visibility;
  58512. },
  58513. enumerable: true,
  58514. configurable: true
  58515. });
  58516. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58517. get: function () {
  58518. return this._sourceMesh.skeleton;
  58519. },
  58520. enumerable: true,
  58521. configurable: true
  58522. });
  58523. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58524. get: function () {
  58525. return this._sourceMesh.renderingGroupId;
  58526. },
  58527. set: function (value) {
  58528. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58529. return;
  58530. }
  58531. //no-op with warning
  58532. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58533. },
  58534. enumerable: true,
  58535. configurable: true
  58536. });
  58537. /**
  58538. * Returns the total number of vertices (integer).
  58539. */
  58540. InstancedMesh.prototype.getTotalVertices = function () {
  58541. return this._sourceMesh.getTotalVertices();
  58542. };
  58543. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58544. get: function () {
  58545. return this._sourceMesh;
  58546. },
  58547. enumerable: true,
  58548. configurable: true
  58549. });
  58550. /**
  58551. * Is this node ready to be used/rendered
  58552. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58553. * @return {boolean} is it ready
  58554. */
  58555. InstancedMesh.prototype.isReady = function (completeCheck) {
  58556. if (completeCheck === void 0) { completeCheck = false; }
  58557. return this._sourceMesh.isReady(completeCheck, true);
  58558. };
  58559. /**
  58560. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58561. */
  58562. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58563. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58564. };
  58565. /**
  58566. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58567. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58568. * The `data` are either a numeric array either a Float32Array.
  58569. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58570. * 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).
  58571. * Note that a new underlying VertexBuffer object is created each call.
  58572. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58573. *
  58574. * Possible `kind` values :
  58575. * - BABYLON.VertexBuffer.PositionKind
  58576. * - BABYLON.VertexBuffer.UVKind
  58577. * - BABYLON.VertexBuffer.UV2Kind
  58578. * - BABYLON.VertexBuffer.UV3Kind
  58579. * - BABYLON.VertexBuffer.UV4Kind
  58580. * - BABYLON.VertexBuffer.UV5Kind
  58581. * - BABYLON.VertexBuffer.UV6Kind
  58582. * - BABYLON.VertexBuffer.ColorKind
  58583. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58584. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58585. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58586. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58587. *
  58588. * Returns the Mesh.
  58589. */
  58590. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58591. if (this.sourceMesh) {
  58592. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58593. }
  58594. return this.sourceMesh;
  58595. };
  58596. /**
  58597. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58598. * If the mesh has no geometry, it is simply returned as it is.
  58599. * The `data` are either a numeric array either a Float32Array.
  58600. * No new underlying VertexBuffer object is created.
  58601. * 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.
  58602. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58603. *
  58604. * Possible `kind` values :
  58605. * - BABYLON.VertexBuffer.PositionKind
  58606. * - BABYLON.VertexBuffer.UVKind
  58607. * - BABYLON.VertexBuffer.UV2Kind
  58608. * - BABYLON.VertexBuffer.UV3Kind
  58609. * - BABYLON.VertexBuffer.UV4Kind
  58610. * - BABYLON.VertexBuffer.UV5Kind
  58611. * - BABYLON.VertexBuffer.UV6Kind
  58612. * - BABYLON.VertexBuffer.ColorKind
  58613. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58614. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58615. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58616. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58617. *
  58618. * Returns the Mesh.
  58619. */
  58620. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58621. if (this.sourceMesh) {
  58622. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58623. }
  58624. return this.sourceMesh;
  58625. };
  58626. /**
  58627. * Sets the mesh indices.
  58628. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58629. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58630. * This method creates a new index buffer each call.
  58631. * Returns the Mesh.
  58632. */
  58633. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58634. if (totalVertices === void 0) { totalVertices = null; }
  58635. if (this.sourceMesh) {
  58636. this.sourceMesh.setIndices(indices, totalVertices);
  58637. }
  58638. return this.sourceMesh;
  58639. };
  58640. /**
  58641. * Boolean : True if the mesh owns the requested kind of data.
  58642. */
  58643. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58644. return this._sourceMesh.isVerticesDataPresent(kind);
  58645. };
  58646. /**
  58647. * Returns an array of indices (IndicesArray).
  58648. */
  58649. InstancedMesh.prototype.getIndices = function () {
  58650. return this._sourceMesh.getIndices();
  58651. };
  58652. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58653. get: function () {
  58654. return this._sourceMesh._positions;
  58655. },
  58656. enumerable: true,
  58657. configurable: true
  58658. });
  58659. /**
  58660. * Sets a new updated BoundingInfo to the mesh.
  58661. * Returns the mesh.
  58662. */
  58663. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58664. var meshBB = this._sourceMesh.getBoundingInfo();
  58665. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58666. this._updateBoundingInfo();
  58667. return this;
  58668. };
  58669. InstancedMesh.prototype._preActivate = function () {
  58670. if (this._currentLOD) {
  58671. this._currentLOD._preActivate();
  58672. }
  58673. return this;
  58674. };
  58675. InstancedMesh.prototype._activate = function (renderId) {
  58676. if (this._currentLOD) {
  58677. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58678. }
  58679. return this;
  58680. };
  58681. /**
  58682. * Returns the current associated LOD AbstractMesh.
  58683. */
  58684. InstancedMesh.prototype.getLOD = function (camera) {
  58685. if (!camera) {
  58686. return this;
  58687. }
  58688. var boundingInfo = this.getBoundingInfo();
  58689. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58690. if (this._currentLOD === this.sourceMesh) {
  58691. return this;
  58692. }
  58693. return this._currentLOD;
  58694. };
  58695. InstancedMesh.prototype._syncSubMeshes = function () {
  58696. this.releaseSubMeshes();
  58697. if (this._sourceMesh.subMeshes) {
  58698. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58699. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58700. }
  58701. }
  58702. return this;
  58703. };
  58704. InstancedMesh.prototype._generatePointsArray = function () {
  58705. return this._sourceMesh._generatePointsArray();
  58706. };
  58707. /**
  58708. * Creates a new InstancedMesh from the current mesh.
  58709. * - name (string) : the cloned mesh name
  58710. * - newParent (optional Node) : the optional Node to parent the clone to.
  58711. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58712. *
  58713. * Returns the clone.
  58714. */
  58715. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58716. var result = this._sourceMesh.createInstance(name);
  58717. // Deep copy
  58718. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58719. // Bounding info
  58720. this.refreshBoundingInfo();
  58721. // Parent
  58722. if (newParent) {
  58723. result.parent = newParent;
  58724. }
  58725. if (!doNotCloneChildren) {
  58726. // Children
  58727. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58728. var mesh = this.getScene().meshes[index];
  58729. if (mesh.parent === this) {
  58730. mesh.clone(mesh.name, result);
  58731. }
  58732. }
  58733. }
  58734. result.computeWorldMatrix(true);
  58735. return result;
  58736. };
  58737. /**
  58738. * Disposes the InstancedMesh.
  58739. * Returns nothing.
  58740. */
  58741. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58742. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58743. // Remove from mesh
  58744. var index = this._sourceMesh.instances.indexOf(this);
  58745. this._sourceMesh.instances.splice(index, 1);
  58746. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58747. };
  58748. return InstancedMesh;
  58749. }(BABYLON.AbstractMesh));
  58750. BABYLON.InstancedMesh = InstancedMesh;
  58751. })(BABYLON || (BABYLON = {}));
  58752. //# sourceMappingURL=babylon.instancedMesh.js.map
  58753. var BABYLON;
  58754. (function (BABYLON) {
  58755. var LinesMesh = /** @class */ (function (_super) {
  58756. __extends(LinesMesh, _super);
  58757. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58758. if (scene === void 0) { scene = null; }
  58759. if (parent === void 0) { parent = null; }
  58760. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58761. _this.useVertexColor = useVertexColor;
  58762. _this.useVertexAlpha = useVertexAlpha;
  58763. _this.color = new BABYLON.Color3(1, 1, 1);
  58764. _this.alpha = 1;
  58765. if (source) {
  58766. _this.color = source.color.clone();
  58767. _this.alpha = source.alpha;
  58768. _this.useVertexColor = source.useVertexColor;
  58769. _this.useVertexAlpha = source.useVertexAlpha;
  58770. }
  58771. _this._intersectionThreshold = 0.1;
  58772. var defines = [];
  58773. var options = {
  58774. attributes: [BABYLON.VertexBuffer.PositionKind],
  58775. uniforms: ["world", "viewProjection"],
  58776. needAlphaBlending: true,
  58777. defines: defines
  58778. };
  58779. if (useVertexAlpha === false) {
  58780. options.needAlphaBlending = false;
  58781. }
  58782. if (!useVertexColor) {
  58783. options.uniforms.push("color");
  58784. }
  58785. else {
  58786. options.defines.push("#define VERTEXCOLOR");
  58787. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58788. }
  58789. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58790. return _this;
  58791. }
  58792. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58793. /**
  58794. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58795. * This margin is expressed in world space coordinates, so its value may vary.
  58796. * Default value is 0.1
  58797. * @returns the intersection Threshold value.
  58798. */
  58799. get: function () {
  58800. return this._intersectionThreshold;
  58801. },
  58802. /**
  58803. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58804. * This margin is expressed in world space coordinates, so its value may vary.
  58805. * @param value the new threshold to apply
  58806. */
  58807. set: function (value) {
  58808. if (this._intersectionThreshold === value) {
  58809. return;
  58810. }
  58811. this._intersectionThreshold = value;
  58812. if (this.geometry) {
  58813. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58814. }
  58815. },
  58816. enumerable: true,
  58817. configurable: true
  58818. });
  58819. /**
  58820. * Returns the string "LineMesh"
  58821. */
  58822. LinesMesh.prototype.getClassName = function () {
  58823. return "LinesMesh";
  58824. };
  58825. Object.defineProperty(LinesMesh.prototype, "material", {
  58826. /**
  58827. * @hidden
  58828. */
  58829. get: function () {
  58830. return this._colorShader;
  58831. },
  58832. /**
  58833. * @hidden
  58834. */
  58835. set: function (value) {
  58836. // Do nothing
  58837. },
  58838. enumerable: true,
  58839. configurable: true
  58840. });
  58841. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58842. /**
  58843. * @hidden
  58844. */
  58845. get: function () {
  58846. return false;
  58847. },
  58848. enumerable: true,
  58849. configurable: true
  58850. });
  58851. LinesMesh.prototype.createInstance = function (name) {
  58852. throw new Error("LinesMeshes do not support createInstance.");
  58853. };
  58854. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58855. if (!this._geometry) {
  58856. return this;
  58857. }
  58858. // VBOs
  58859. this._geometry._bind(this._colorShader.getEffect());
  58860. // Color
  58861. if (!this.useVertexColor) {
  58862. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58863. }
  58864. return this;
  58865. };
  58866. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58867. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58868. return this;
  58869. }
  58870. var engine = this.getScene().getEngine();
  58871. // Draw order
  58872. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58873. return this;
  58874. };
  58875. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58876. this._colorShader.dispose();
  58877. _super.prototype.dispose.call(this, doNotRecurse);
  58878. };
  58879. /**
  58880. * Returns a new LineMesh object cloned from the current one.
  58881. */
  58882. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58883. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58884. };
  58885. return LinesMesh;
  58886. }(BABYLON.Mesh));
  58887. BABYLON.LinesMesh = LinesMesh;
  58888. })(BABYLON || (BABYLON = {}));
  58889. //# sourceMappingURL=babylon.linesMesh.js.map
  58890. var BABYLON;
  58891. (function (BABYLON) {
  58892. /**
  58893. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58894. * The underlying implementation relies on an associative array to ensure the best performances.
  58895. * The value can be anything including 'null' but except 'undefined'
  58896. */
  58897. var StringDictionary = /** @class */ (function () {
  58898. function StringDictionary() {
  58899. this._count = 0;
  58900. this._data = {};
  58901. }
  58902. /**
  58903. * This will clear this dictionary and copy the content from the 'source' one.
  58904. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58905. * @param source the dictionary to take the content from and copy to this dictionary
  58906. */
  58907. StringDictionary.prototype.copyFrom = function (source) {
  58908. var _this = this;
  58909. this.clear();
  58910. source.forEach(function (t, v) { return _this.add(t, v); });
  58911. };
  58912. /**
  58913. * Get a value based from its key
  58914. * @param key the given key to get the matching value from
  58915. * @return the value if found, otherwise undefined is returned
  58916. */
  58917. StringDictionary.prototype.get = function (key) {
  58918. var val = this._data[key];
  58919. if (val !== undefined) {
  58920. return val;
  58921. }
  58922. return undefined;
  58923. };
  58924. /**
  58925. * Get a value from its key or add it if it doesn't exist.
  58926. * This method will ensure you that a given key/data will be present in the dictionary.
  58927. * @param key the given key to get the matching value from
  58928. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58929. * The factory will only be invoked if there's no data for the given key.
  58930. * @return the value corresponding to the key.
  58931. */
  58932. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58933. var val = this.get(key);
  58934. if (val !== undefined) {
  58935. return val;
  58936. }
  58937. val = factory(key);
  58938. if (val) {
  58939. this.add(key, val);
  58940. }
  58941. return val;
  58942. };
  58943. /**
  58944. * Get a value from its key if present in the dictionary otherwise add it
  58945. * @param key the key to get the value from
  58946. * @param val if there's no such key/value pair in the dictionary add it with this value
  58947. * @return the value corresponding to the key
  58948. */
  58949. StringDictionary.prototype.getOrAdd = function (key, val) {
  58950. var curVal = this.get(key);
  58951. if (curVal !== undefined) {
  58952. return curVal;
  58953. }
  58954. this.add(key, val);
  58955. return val;
  58956. };
  58957. /**
  58958. * Check if there's a given key in the dictionary
  58959. * @param key the key to check for
  58960. * @return true if the key is present, false otherwise
  58961. */
  58962. StringDictionary.prototype.contains = function (key) {
  58963. return this._data[key] !== undefined;
  58964. };
  58965. /**
  58966. * Add a new key and its corresponding value
  58967. * @param key the key to add
  58968. * @param value the value corresponding to the key
  58969. * @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
  58970. */
  58971. StringDictionary.prototype.add = function (key, value) {
  58972. if (this._data[key] !== undefined) {
  58973. return false;
  58974. }
  58975. this._data[key] = value;
  58976. ++this._count;
  58977. return true;
  58978. };
  58979. StringDictionary.prototype.set = function (key, value) {
  58980. if (this._data[key] === undefined) {
  58981. return false;
  58982. }
  58983. this._data[key] = value;
  58984. return true;
  58985. };
  58986. /**
  58987. * Get the element of the given key and remove it from the dictionary
  58988. * @param key
  58989. */
  58990. StringDictionary.prototype.getAndRemove = function (key) {
  58991. var val = this.get(key);
  58992. if (val !== undefined) {
  58993. delete this._data[key];
  58994. --this._count;
  58995. return val;
  58996. }
  58997. return null;
  58998. };
  58999. /**
  59000. * Remove a key/value from the dictionary.
  59001. * @param key the key to remove
  59002. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59003. */
  59004. StringDictionary.prototype.remove = function (key) {
  59005. if (this.contains(key)) {
  59006. delete this._data[key];
  59007. --this._count;
  59008. return true;
  59009. }
  59010. return false;
  59011. };
  59012. /**
  59013. * Clear the whole content of the dictionary
  59014. */
  59015. StringDictionary.prototype.clear = function () {
  59016. this._data = {};
  59017. this._count = 0;
  59018. };
  59019. Object.defineProperty(StringDictionary.prototype, "count", {
  59020. get: function () {
  59021. return this._count;
  59022. },
  59023. enumerable: true,
  59024. configurable: true
  59025. });
  59026. /**
  59027. * Execute a callback on each key/val of the dictionary.
  59028. * Note that you can remove any element in this dictionary in the callback implementation
  59029. * @param callback the callback to execute on a given key/value pair
  59030. */
  59031. StringDictionary.prototype.forEach = function (callback) {
  59032. for (var cur in this._data) {
  59033. var val = this._data[cur];
  59034. callback(cur, val);
  59035. }
  59036. };
  59037. /**
  59038. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59039. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59040. * Note that you can remove any element in this dictionary in the callback implementation
  59041. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59042. */
  59043. StringDictionary.prototype.first = function (callback) {
  59044. for (var cur in this._data) {
  59045. var val = this._data[cur];
  59046. var res = callback(cur, val);
  59047. if (res) {
  59048. return res;
  59049. }
  59050. }
  59051. return null;
  59052. };
  59053. return StringDictionary;
  59054. }());
  59055. BABYLON.StringDictionary = StringDictionary;
  59056. })(BABYLON || (BABYLON = {}));
  59057. //# sourceMappingURL=babylon.stringDictionary.js.map
  59058. var BABYLON;
  59059. (function (BABYLON) {
  59060. var Debug;
  59061. (function (Debug) {
  59062. /**
  59063. * Class used to render a debug view of a given skeleton
  59064. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  59065. */
  59066. var SkeletonViewer = /** @class */ (function () {
  59067. /**
  59068. * Creates a new SkeletonViewer
  59069. * @param skeleton defines the skeleton to render
  59070. * @param mesh defines the mesh attached to the skeleton
  59071. * @param scene defines the hosting scene
  59072. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  59073. * @param renderingGroupId defines the rendering group id to use with the viewer
  59074. */
  59075. function SkeletonViewer(
  59076. /** defines the skeleton to render */
  59077. skeleton,
  59078. /** defines the mesh attached to the skeleton */
  59079. mesh, scene,
  59080. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  59081. autoUpdateBonesMatrices,
  59082. /** defines the rendering group id to use with the viewer */
  59083. renderingGroupId) {
  59084. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59085. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59086. this.skeleton = skeleton;
  59087. this.mesh = mesh;
  59088. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59089. this.renderingGroupId = renderingGroupId;
  59090. /** Gets or sets the color used to render the skeleton */
  59091. this.color = BABYLON.Color3.White();
  59092. this._debugLines = new Array();
  59093. this._isEnabled = false;
  59094. this._scene = scene;
  59095. this.update();
  59096. this._renderFunction = this.update.bind(this);
  59097. }
  59098. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59099. get: function () {
  59100. return this._isEnabled;
  59101. },
  59102. /** Gets or sets a boolean indicating if the viewer is enabled */
  59103. set: function (value) {
  59104. if (this._isEnabled === value) {
  59105. return;
  59106. }
  59107. this._isEnabled = value;
  59108. if (value) {
  59109. this._scene.registerBeforeRender(this._renderFunction);
  59110. }
  59111. else {
  59112. this._scene.unregisterBeforeRender(this._renderFunction);
  59113. }
  59114. },
  59115. enumerable: true,
  59116. configurable: true
  59117. });
  59118. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59119. if (x === void 0) { x = 0; }
  59120. if (y === void 0) { y = 0; }
  59121. if (z === void 0) { z = 0; }
  59122. var tmat = BABYLON.Tmp.Matrix[0];
  59123. var parentBone = bone.getParent();
  59124. tmat.copyFrom(bone.getLocalMatrix());
  59125. if (x !== 0 || y !== 0 || z !== 0) {
  59126. var tmat2 = BABYLON.Tmp.Matrix[1];
  59127. BABYLON.Matrix.IdentityToRef(tmat2);
  59128. tmat2.m[12] = x;
  59129. tmat2.m[13] = y;
  59130. tmat2.m[14] = z;
  59131. tmat2.multiplyToRef(tmat, tmat);
  59132. }
  59133. if (parentBone) {
  59134. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59135. }
  59136. tmat.multiplyToRef(meshMat, tmat);
  59137. position.x = tmat.m[12];
  59138. position.y = tmat.m[13];
  59139. position.z = tmat.m[14];
  59140. };
  59141. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59142. var len = bones.length;
  59143. var meshPos = this.mesh.position;
  59144. for (var i = 0; i < len; i++) {
  59145. var bone = bones[i];
  59146. var points = this._debugLines[i];
  59147. if (!points) {
  59148. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59149. this._debugLines[i] = points;
  59150. }
  59151. this._getBonePosition(points[0], bone, meshMat);
  59152. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59153. points[0].subtractInPlace(meshPos);
  59154. points[1].subtractInPlace(meshPos);
  59155. }
  59156. };
  59157. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59158. var len = bones.length;
  59159. var boneNum = 0;
  59160. var meshPos = this.mesh.position;
  59161. for (var i = len - 1; i >= 0; i--) {
  59162. var childBone = bones[i];
  59163. var parentBone = childBone.getParent();
  59164. if (!parentBone) {
  59165. continue;
  59166. }
  59167. var points = this._debugLines[boneNum];
  59168. if (!points) {
  59169. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59170. this._debugLines[boneNum] = points;
  59171. }
  59172. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59173. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59174. points[0].subtractInPlace(meshPos);
  59175. points[1].subtractInPlace(meshPos);
  59176. boneNum++;
  59177. }
  59178. };
  59179. /** Update the viewer to sync with current skeleton state */
  59180. SkeletonViewer.prototype.update = function () {
  59181. if (this.autoUpdateBonesMatrices) {
  59182. this.skeleton.computeAbsoluteTransforms();
  59183. }
  59184. if (this.skeleton.bones[0].length === undefined) {
  59185. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59186. }
  59187. else {
  59188. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59189. }
  59190. if (!this._debugMesh) {
  59191. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  59192. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59193. }
  59194. else {
  59195. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59196. }
  59197. this._debugMesh.position.copyFrom(this.mesh.position);
  59198. this._debugMesh.color = this.color;
  59199. };
  59200. /** Release associated resources */
  59201. SkeletonViewer.prototype.dispose = function () {
  59202. if (this._debugMesh) {
  59203. this.isEnabled = false;
  59204. this._debugMesh.dispose();
  59205. this._debugMesh = null;
  59206. }
  59207. };
  59208. return SkeletonViewer;
  59209. }());
  59210. Debug.SkeletonViewer = SkeletonViewer;
  59211. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59212. })(BABYLON || (BABYLON = {}));
  59213. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59214. /**
  59215. * Module Debug contains the (visual) components to debug a scene correctly
  59216. */
  59217. var BABYLON;
  59218. (function (BABYLON) {
  59219. var Debug;
  59220. (function (Debug) {
  59221. /**
  59222. * The Axes viewer will show 3 axes in a specific point in space
  59223. */
  59224. var AxesViewer = /** @class */ (function () {
  59225. /**
  59226. * Creates a new AxesViewer
  59227. * @param scene defines the hosting scene
  59228. * @param scaleLines defines a number used to scale line length (1 by default)
  59229. */
  59230. function AxesViewer(scene, scaleLines) {
  59231. if (scaleLines === void 0) { scaleLines = 1; }
  59232. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59233. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59234. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59235. /**
  59236. * Gets or sets a number used to scale line length
  59237. */
  59238. this.scaleLines = 1;
  59239. this.scaleLines = scaleLines;
  59240. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59241. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59242. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59243. this._xmesh.renderingGroupId = 2;
  59244. this._ymesh.renderingGroupId = 2;
  59245. this._zmesh.renderingGroupId = 2;
  59246. this._xmesh.material.checkReadyOnlyOnce = true;
  59247. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59248. this._ymesh.material.checkReadyOnlyOnce = true;
  59249. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59250. this._zmesh.material.checkReadyOnlyOnce = true;
  59251. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59252. this.scene = scene;
  59253. }
  59254. /**
  59255. * Force the viewer to update
  59256. * @param position defines the position of the viewer
  59257. * @param xaxis defines the x axis of the viewer
  59258. * @param yaxis defines the y axis of the viewer
  59259. * @param zaxis defines the z axis of the viewer
  59260. */
  59261. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59262. var scaleLines = this.scaleLines;
  59263. if (this._xmesh) {
  59264. this._xmesh.position.copyFrom(position);
  59265. }
  59266. if (this._ymesh) {
  59267. this._ymesh.position.copyFrom(position);
  59268. }
  59269. if (this._zmesh) {
  59270. this._zmesh.position.copyFrom(position);
  59271. }
  59272. var point2 = this._xline[1];
  59273. point2.x = xaxis.x * scaleLines;
  59274. point2.y = xaxis.y * scaleLines;
  59275. point2.z = xaxis.z * scaleLines;
  59276. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  59277. point2 = this._yline[1];
  59278. point2.x = yaxis.x * scaleLines;
  59279. point2.y = yaxis.y * scaleLines;
  59280. point2.z = yaxis.z * scaleLines;
  59281. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  59282. point2 = this._zline[1];
  59283. point2.x = zaxis.x * scaleLines;
  59284. point2.y = zaxis.y * scaleLines;
  59285. point2.z = zaxis.z * scaleLines;
  59286. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  59287. };
  59288. /** Releases resources */
  59289. AxesViewer.prototype.dispose = function () {
  59290. if (this._xmesh) {
  59291. this._xmesh.dispose();
  59292. }
  59293. if (this._ymesh) {
  59294. this._ymesh.dispose();
  59295. }
  59296. if (this._zmesh) {
  59297. this._zmesh.dispose();
  59298. }
  59299. this._xmesh = null;
  59300. this._ymesh = null;
  59301. this._zmesh = null;
  59302. this.scene = null;
  59303. };
  59304. return AxesViewer;
  59305. }());
  59306. Debug.AxesViewer = AxesViewer;
  59307. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59308. })(BABYLON || (BABYLON = {}));
  59309. //# sourceMappingURL=babylon.axesViewer.js.map
  59310. var BABYLON;
  59311. (function (BABYLON) {
  59312. var Debug;
  59313. (function (Debug) {
  59314. /**
  59315. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  59316. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  59317. */
  59318. var BoneAxesViewer = /** @class */ (function (_super) {
  59319. __extends(BoneAxesViewer, _super);
  59320. /**
  59321. * Creates a new BoneAxesViewer
  59322. * @param scene defines the hosting scene
  59323. * @param bone defines the target bone
  59324. * @param mesh defines the target mesh
  59325. * @param scaleLines defines a scaling factor for line length (1 by default)
  59326. */
  59327. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59328. if (scaleLines === void 0) { scaleLines = 1; }
  59329. var _this = _super.call(this, scene, scaleLines) || this;
  59330. /** Gets current position */
  59331. _this.pos = BABYLON.Vector3.Zero();
  59332. /** Gets direction of X axis */
  59333. _this.xaxis = BABYLON.Vector3.Zero();
  59334. /** Gets direction of Y axis */
  59335. _this.yaxis = BABYLON.Vector3.Zero();
  59336. /** Gets direction of Z axis */
  59337. _this.zaxis = BABYLON.Vector3.Zero();
  59338. _this.mesh = mesh;
  59339. _this.bone = bone;
  59340. return _this;
  59341. }
  59342. /**
  59343. * Force the viewer to update
  59344. */
  59345. BoneAxesViewer.prototype.update = function () {
  59346. if (!this.mesh || !this.bone) {
  59347. return;
  59348. }
  59349. var bone = this.bone;
  59350. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59351. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59352. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59353. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59354. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59355. };
  59356. /** Releases resources */
  59357. BoneAxesViewer.prototype.dispose = function () {
  59358. if (this.mesh) {
  59359. this.mesh = null;
  59360. this.bone = null;
  59361. _super.prototype.dispose.call(this);
  59362. }
  59363. };
  59364. return BoneAxesViewer;
  59365. }(Debug.AxesViewer));
  59366. Debug.BoneAxesViewer = BoneAxesViewer;
  59367. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59368. })(BABYLON || (BABYLON = {}));
  59369. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59370. var BABYLON;
  59371. (function (BABYLON) {
  59372. var RayHelper = /** @class */ (function () {
  59373. function RayHelper(ray) {
  59374. this.ray = ray;
  59375. }
  59376. RayHelper.CreateAndShow = function (ray, scene, color) {
  59377. var helper = new RayHelper(ray);
  59378. helper.show(scene, color);
  59379. return helper;
  59380. };
  59381. RayHelper.prototype.show = function (scene, color) {
  59382. if (!this._renderFunction && this.ray) {
  59383. var ray = this.ray;
  59384. this._renderFunction = this._render.bind(this);
  59385. this._scene = scene;
  59386. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59387. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59388. if (this._renderFunction) {
  59389. this._scene.registerBeforeRender(this._renderFunction);
  59390. }
  59391. }
  59392. if (color && this._renderLine) {
  59393. this._renderLine.color.copyFrom(color);
  59394. }
  59395. };
  59396. RayHelper.prototype.hide = function () {
  59397. if (this._renderFunction && this._scene) {
  59398. this._scene.unregisterBeforeRender(this._renderFunction);
  59399. this._scene = null;
  59400. this._renderFunction = null;
  59401. if (this._renderLine) {
  59402. this._renderLine.dispose();
  59403. this._renderLine = null;
  59404. }
  59405. this._renderPoints = [];
  59406. }
  59407. };
  59408. RayHelper.prototype._render = function () {
  59409. var ray = this.ray;
  59410. if (!ray) {
  59411. return;
  59412. }
  59413. var point = this._renderPoints[1];
  59414. var len = Math.min(ray.length, 1000000);
  59415. point.copyFrom(ray.direction);
  59416. point.scaleInPlace(len);
  59417. point.addInPlace(ray.origin);
  59418. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59419. };
  59420. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59421. this._attachedToMesh = mesh;
  59422. var ray = this.ray;
  59423. if (!ray) {
  59424. return;
  59425. }
  59426. if (!ray.direction) {
  59427. ray.direction = BABYLON.Vector3.Zero();
  59428. }
  59429. if (!ray.origin) {
  59430. ray.origin = BABYLON.Vector3.Zero();
  59431. }
  59432. if (length) {
  59433. ray.length = length;
  59434. }
  59435. if (!meshSpaceOrigin) {
  59436. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59437. }
  59438. if (!meshSpaceDirection) {
  59439. // -1 so that this will work with Mesh.lookAt
  59440. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59441. }
  59442. if (!this._meshSpaceDirection) {
  59443. this._meshSpaceDirection = meshSpaceDirection.clone();
  59444. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  59445. }
  59446. else {
  59447. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  59448. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  59449. }
  59450. if (!this._updateToMeshFunction) {
  59451. this._updateToMeshFunction = this._updateToMesh.bind(this);
  59452. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  59453. }
  59454. this._updateToMesh();
  59455. };
  59456. RayHelper.prototype.detachFromMesh = function () {
  59457. if (this._attachedToMesh) {
  59458. if (this._updateToMeshFunction) {
  59459. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  59460. }
  59461. this._attachedToMesh = null;
  59462. this._updateToMeshFunction = null;
  59463. }
  59464. };
  59465. RayHelper.prototype._updateToMesh = function () {
  59466. var ray = this.ray;
  59467. if (!this._attachedToMesh || !ray) {
  59468. return;
  59469. }
  59470. if (this._attachedToMesh._isDisposed) {
  59471. this.detachFromMesh();
  59472. return;
  59473. }
  59474. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  59475. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  59476. };
  59477. RayHelper.prototype.dispose = function () {
  59478. this.hide();
  59479. this.detachFromMesh();
  59480. this.ray = null;
  59481. };
  59482. return RayHelper;
  59483. }());
  59484. BABYLON.RayHelper = RayHelper;
  59485. })(BABYLON || (BABYLON = {}));
  59486. //# sourceMappingURL=babylon.rayHelper.js.map
  59487. var BABYLON;
  59488. (function (BABYLON) {
  59489. // load the inspector using require, if not present in the global namespace.
  59490. var DebugLayer = /** @class */ (function () {
  59491. function DebugLayer(scene) {
  59492. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59493. this.onPropertyChangedObservable = new BABYLON.Observable();
  59494. this._scene = scene;
  59495. }
  59496. /** Creates the inspector window. */
  59497. DebugLayer.prototype._createInspector = function (config) {
  59498. if (config === void 0) { config = {}; }
  59499. var popup = config.popup || false;
  59500. var initialTab = config.initialTab || 0;
  59501. var parentElement = config.parentElement || null;
  59502. if (!this._inspector) {
  59503. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59504. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59505. } // else nothing to do as instance is already created
  59506. };
  59507. DebugLayer.prototype.isVisible = function () {
  59508. if (!this._inspector) {
  59509. return false;
  59510. }
  59511. return true;
  59512. };
  59513. DebugLayer.prototype.hide = function () {
  59514. if (this._inspector) {
  59515. try {
  59516. this._inspector.dispose();
  59517. }
  59518. catch (e) {
  59519. // If the inspector has been removed directly from the inspector tool
  59520. }
  59521. this.onPropertyChangedObservable.clear();
  59522. this._inspector = null;
  59523. }
  59524. };
  59525. /**
  59526. *
  59527. * Launch the debugLayer.
  59528. *
  59529. * initialTab:
  59530. * | Value | Tab Name |
  59531. * | --- | --- |
  59532. * | 0 | Scene |
  59533. * | 1 | Console |
  59534. * | 2 | Stats |
  59535. * | 3 | Textures |
  59536. * | 4 | Mesh |
  59537. * | 5 | Light |
  59538. * | 6 | Material |
  59539. * | 7 | GLTF |
  59540. * | 8 | GUI |
  59541. * | 9 | Physics |
  59542. * | 10 | Camera |
  59543. * | 11 | Audio |
  59544. *
  59545. */
  59546. DebugLayer.prototype.show = function (config) {
  59547. if (config === void 0) { config = {}; }
  59548. if (typeof this.BJSINSPECTOR == 'undefined') {
  59549. // Load inspector and add it to the DOM
  59550. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59551. }
  59552. else {
  59553. // Otherwise creates the inspector
  59554. this._createInspector(config);
  59555. }
  59556. };
  59557. /**
  59558. * Gets the active tab
  59559. * @return the index of the active tab or -1 if the inspector is hidden
  59560. */
  59561. DebugLayer.prototype.getActiveTab = function () {
  59562. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  59563. };
  59564. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  59565. return DebugLayer;
  59566. }());
  59567. BABYLON.DebugLayer = DebugLayer;
  59568. })(BABYLON || (BABYLON = {}));
  59569. //# sourceMappingURL=babylon.debugLayer.js.map
  59570. var BABYLON;
  59571. (function (BABYLON) {
  59572. var Debug;
  59573. (function (Debug) {
  59574. /**
  59575. * Used to show the physics impostor around the specific mesh
  59576. */
  59577. var PhysicsViewer = /** @class */ (function () {
  59578. /**
  59579. * Creates a new PhysicsViewer
  59580. * @param scene defines the hosting scene
  59581. */
  59582. function PhysicsViewer(scene) {
  59583. /** @hidden */
  59584. this._impostors = [];
  59585. /** @hidden */
  59586. this._meshes = [];
  59587. /** @hidden */
  59588. this._numMeshes = 0;
  59589. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59590. var physicEngine = this._scene.getPhysicsEngine();
  59591. if (physicEngine) {
  59592. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59593. }
  59594. }
  59595. /** @hidden */
  59596. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59597. var plugin = this._physicsEnginePlugin;
  59598. for (var i = 0; i < this._numMeshes; i++) {
  59599. var impostor = this._impostors[i];
  59600. if (!impostor) {
  59601. continue;
  59602. }
  59603. if (impostor.isDisposed) {
  59604. this.hideImpostor(this._impostors[i--]);
  59605. }
  59606. else {
  59607. var mesh = this._meshes[i];
  59608. if (mesh && plugin) {
  59609. plugin.syncMeshWithImpostor(mesh, impostor);
  59610. }
  59611. }
  59612. }
  59613. };
  59614. /**
  59615. * Renders a specified physic impostor
  59616. * @param impostor defines the impostor to render
  59617. */
  59618. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59619. if (!this._scene) {
  59620. return;
  59621. }
  59622. for (var i = 0; i < this._numMeshes; i++) {
  59623. if (this._impostors[i] == impostor) {
  59624. return;
  59625. }
  59626. }
  59627. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59628. if (debugMesh) {
  59629. this._impostors[this._numMeshes] = impostor;
  59630. this._meshes[this._numMeshes] = debugMesh;
  59631. if (this._numMeshes === 0) {
  59632. this._renderFunction = this._updateDebugMeshes.bind(this);
  59633. this._scene.registerBeforeRender(this._renderFunction);
  59634. }
  59635. this._numMeshes++;
  59636. }
  59637. };
  59638. /**
  59639. * Hides a specified physic impostor
  59640. * @param impostor defines the impostor to hide
  59641. */
  59642. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59643. if (!impostor || !this._scene) {
  59644. return;
  59645. }
  59646. var removed = false;
  59647. for (var i = 0; i < this._numMeshes; i++) {
  59648. if (this._impostors[i] == impostor) {
  59649. var mesh = this._meshes[i];
  59650. if (!mesh) {
  59651. continue;
  59652. }
  59653. this._scene.removeMesh(mesh);
  59654. mesh.dispose();
  59655. this._numMeshes--;
  59656. if (this._numMeshes > 0) {
  59657. this._meshes[i] = this._meshes[this._numMeshes];
  59658. this._impostors[i] = this._impostors[this._numMeshes];
  59659. this._meshes[this._numMeshes] = null;
  59660. this._impostors[this._numMeshes] = null;
  59661. }
  59662. else {
  59663. this._meshes[0] = null;
  59664. this._impostors[0] = null;
  59665. }
  59666. removed = true;
  59667. break;
  59668. }
  59669. }
  59670. if (removed && this._numMeshes === 0) {
  59671. this._scene.unregisterBeforeRender(this._renderFunction);
  59672. }
  59673. };
  59674. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59675. if (!this._debugMaterial) {
  59676. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59677. this._debugMaterial.wireframe = true;
  59678. }
  59679. return this._debugMaterial;
  59680. };
  59681. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  59682. if (!this._debugBoxMesh) {
  59683. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59684. this._debugBoxMesh.renderingGroupId = 1;
  59685. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59686. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59687. scene.removeMesh(this._debugBoxMesh);
  59688. }
  59689. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59690. };
  59691. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  59692. if (!this._debugSphereMesh) {
  59693. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59694. this._debugSphereMesh.renderingGroupId = 1;
  59695. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59696. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59697. scene.removeMesh(this._debugSphereMesh);
  59698. }
  59699. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59700. };
  59701. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  59702. var mesh = null;
  59703. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  59704. mesh = this._getDebugBoxMesh(scene);
  59705. impostor.getBoxSizeToRef(mesh.scaling);
  59706. }
  59707. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  59708. mesh = this._getDebugSphereMesh(scene);
  59709. var radius = impostor.getRadius();
  59710. mesh.scaling.x = radius * 2;
  59711. mesh.scaling.y = radius * 2;
  59712. mesh.scaling.z = radius * 2;
  59713. }
  59714. return mesh;
  59715. };
  59716. /** Releases all resources */
  59717. PhysicsViewer.prototype.dispose = function () {
  59718. for (var i = 0; i < this._numMeshes; i++) {
  59719. this.hideImpostor(this._impostors[i]);
  59720. }
  59721. if (this._debugBoxMesh) {
  59722. this._debugBoxMesh.dispose();
  59723. }
  59724. if (this._debugSphereMesh) {
  59725. this._debugSphereMesh.dispose();
  59726. }
  59727. if (this._debugMaterial) {
  59728. this._debugMaterial.dispose();
  59729. }
  59730. this._impostors.length = 0;
  59731. this._scene = null;
  59732. this._physicsEnginePlugin = null;
  59733. };
  59734. return PhysicsViewer;
  59735. }());
  59736. Debug.PhysicsViewer = PhysicsViewer;
  59737. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59738. })(BABYLON || (BABYLON = {}));
  59739. //# sourceMappingURL=babylon.physicsViewer.js.map
  59740. var BABYLON;
  59741. (function (BABYLON) {
  59742. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  59743. get: function () {
  59744. return this._forceShowBoundingBoxes || false;
  59745. },
  59746. set: function (value) {
  59747. this._forceShowBoundingBoxes = value;
  59748. // Lazyly creates a BB renderer if needed.
  59749. if (value) {
  59750. this.getBoundingBoxRenderer();
  59751. }
  59752. },
  59753. enumerable: true,
  59754. configurable: true
  59755. });
  59756. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  59757. if (!this._boundingBoxRenderer) {
  59758. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  59759. }
  59760. return this._boundingBoxRenderer;
  59761. };
  59762. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  59763. get: function () {
  59764. return this._showBoundingBox || false;
  59765. },
  59766. set: function (value) {
  59767. this._showBoundingBox = value;
  59768. // Lazyly creates a BB renderer if needed.
  59769. if (value) {
  59770. this.getScene().getBoundingBoxRenderer();
  59771. }
  59772. },
  59773. enumerable: true,
  59774. configurable: true
  59775. });
  59776. var BoundingBoxRenderer = /** @class */ (function () {
  59777. function BoundingBoxRenderer(scene) {
  59778. /**
  59779. * The component name helpfull to identify the component in the list of scene components.
  59780. */
  59781. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  59782. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59783. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59784. this.showBackLines = true;
  59785. this.renderList = new BABYLON.SmartArray(32);
  59786. this._vertexBuffers = {};
  59787. this.scene = scene;
  59788. scene._addComponent(this);
  59789. }
  59790. /**
  59791. * Registers the component in a given scene
  59792. */
  59793. BoundingBoxRenderer.prototype.register = function () {
  59794. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  59795. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  59796. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  59797. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  59798. };
  59799. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  59800. if (mesh.showSubMeshesBoundingBox) {
  59801. var boundingInfo = subMesh.getBoundingInfo();
  59802. if (boundingInfo !== null && boundingInfo !== undefined) {
  59803. this.renderList.push(boundingInfo.boundingBox);
  59804. }
  59805. }
  59806. };
  59807. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  59808. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  59809. var boundingInfo = sourceMesh.getBoundingInfo();
  59810. this.renderList.push(boundingInfo.boundingBox);
  59811. }
  59812. };
  59813. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59814. if (this._colorShader) {
  59815. return;
  59816. }
  59817. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  59818. attributes: [BABYLON.VertexBuffer.PositionKind],
  59819. uniforms: ["world", "viewProjection", "color"]
  59820. });
  59821. var engine = this.scene.getEngine();
  59822. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  59823. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59824. this._createIndexBuffer();
  59825. };
  59826. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  59827. var engine = this.scene.getEngine();
  59828. 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]);
  59829. };
  59830. /**
  59831. * Rebuilds the elements related to this component in case of
  59832. * context lost for instance.
  59833. */
  59834. BoundingBoxRenderer.prototype.rebuild = function () {
  59835. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59836. if (vb) {
  59837. vb._rebuild();
  59838. }
  59839. this._createIndexBuffer();
  59840. };
  59841. BoundingBoxRenderer.prototype.reset = function () {
  59842. this.renderList.reset();
  59843. };
  59844. BoundingBoxRenderer.prototype.render = function () {
  59845. if (this.renderList.length === 0) {
  59846. return;
  59847. }
  59848. this._prepareRessources();
  59849. if (!this._colorShader.isReady()) {
  59850. return;
  59851. }
  59852. var engine = this.scene.getEngine();
  59853. engine.setDepthWrite(false);
  59854. this._colorShader._preBind();
  59855. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59856. var boundingBox = this.renderList.data[boundingBoxIndex];
  59857. var min = boundingBox.minimum;
  59858. var max = boundingBox.maximum;
  59859. var diff = max.subtract(min);
  59860. var median = min.add(diff.scale(0.5));
  59861. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59862. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59863. .multiply(boundingBox.getWorldMatrix());
  59864. // VBOs
  59865. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59866. if (this.showBackLines) {
  59867. // Back
  59868. engine.setDepthFunctionToGreaterOrEqual();
  59869. this.scene.resetCachedMaterial();
  59870. this._colorShader.setColor4("color", this.backColor.toColor4());
  59871. this._colorShader.bind(worldMatrix);
  59872. // Draw order
  59873. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59874. }
  59875. // Front
  59876. engine.setDepthFunctionToLess();
  59877. this.scene.resetCachedMaterial();
  59878. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59879. this._colorShader.bind(worldMatrix);
  59880. // Draw order
  59881. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59882. }
  59883. this._colorShader.unbind();
  59884. engine.setDepthFunctionToLessOrEqual();
  59885. engine.setDepthWrite(true);
  59886. };
  59887. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  59888. this._prepareRessources();
  59889. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  59890. return;
  59891. }
  59892. var engine = this.scene.getEngine();
  59893. engine.setDepthWrite(false);
  59894. engine.setColorWrite(false);
  59895. this._colorShader._preBind();
  59896. var boundingBox = mesh._boundingInfo.boundingBox;
  59897. var min = boundingBox.minimum;
  59898. var max = boundingBox.maximum;
  59899. var diff = max.subtract(min);
  59900. var median = min.add(diff.scale(0.5));
  59901. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59902. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59903. .multiply(boundingBox.getWorldMatrix());
  59904. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59905. engine.setDepthFunctionToLess();
  59906. this.scene.resetCachedMaterial();
  59907. this._colorShader.bind(worldMatrix);
  59908. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59909. this._colorShader.unbind();
  59910. engine.setDepthFunctionToLessOrEqual();
  59911. engine.setDepthWrite(true);
  59912. engine.setColorWrite(true);
  59913. };
  59914. BoundingBoxRenderer.prototype.dispose = function () {
  59915. if (!this._colorShader) {
  59916. return;
  59917. }
  59918. this.renderList.dispose();
  59919. this._colorShader.dispose();
  59920. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59921. if (buffer) {
  59922. buffer.dispose();
  59923. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59924. }
  59925. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  59926. };
  59927. return BoundingBoxRenderer;
  59928. }());
  59929. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59930. })(BABYLON || (BABYLON = {}));
  59931. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59932. var BABYLON;
  59933. (function (BABYLON) {
  59934. BABYLON.Engine.prototype.createTransformFeedback = function () {
  59935. return this._gl.createTransformFeedback();
  59936. };
  59937. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  59938. this._gl.deleteTransformFeedback(value);
  59939. };
  59940. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  59941. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  59942. };
  59943. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  59944. if (usePoints === void 0) { usePoints = true; }
  59945. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  59946. };
  59947. BABYLON.Engine.prototype.endTransformFeedback = function () {
  59948. this._gl.endTransformFeedback();
  59949. };
  59950. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  59951. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  59952. };
  59953. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  59954. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  59955. };
  59956. })(BABYLON || (BABYLON = {}));
  59957. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  59958. var BABYLON;
  59959. (function (BABYLON) {
  59960. /**
  59961. * This represents a GPU particle system in Babylon
  59962. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  59963. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  59964. */
  59965. var GPUParticleSystem = /** @class */ (function (_super) {
  59966. __extends(GPUParticleSystem, _super);
  59967. /**
  59968. * Instantiates a GPU particle system.
  59969. * 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.
  59970. * @param name The name of the particle system
  59971. * @param options The options used to create the system
  59972. * @param scene The scene the particle system belongs to
  59973. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59974. */
  59975. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59976. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59977. var _this = _super.call(this, name) || this;
  59978. /**
  59979. * The layer mask we are rendering the particles through.
  59980. */
  59981. _this.layerMask = 0x0FFFFFFF;
  59982. _this._accumulatedCount = 0;
  59983. _this._targetIndex = 0;
  59984. _this._currentRenderId = -1;
  59985. _this._started = false;
  59986. _this._stopped = false;
  59987. _this._timeDelta = 0;
  59988. _this._attributesStrideSize = 21;
  59989. _this._actualFrame = 0;
  59990. _this._rawTextureWidth = 256;
  59991. /**
  59992. * An event triggered when the system is disposed.
  59993. */
  59994. _this.onDisposeObservable = new BABYLON.Observable();
  59995. /**
  59996. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59997. * to override the particles.
  59998. */
  59999. _this.forceDepthWrite = false;
  60000. _this._preWarmDone = false;
  60001. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60002. _this._engine = _this._scene.getEngine();
  60003. if (!options.randomTextureSize) {
  60004. delete options.randomTextureSize;
  60005. }
  60006. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60007. var optionsAsNumber = options;
  60008. if (isFinite(optionsAsNumber)) {
  60009. fullOptions.capacity = optionsAsNumber;
  60010. }
  60011. _this._capacity = fullOptions.capacity;
  60012. _this._activeCount = fullOptions.capacity;
  60013. _this._currentActiveCount = 0;
  60014. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60015. _this._scene.particleSystems.push(_this);
  60016. _this._updateEffectOptions = {
  60017. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60018. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60019. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60020. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60021. uniformBuffersNames: [],
  60022. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60023. defines: "",
  60024. fallbacks: null,
  60025. onCompiled: null,
  60026. onError: null,
  60027. indexParameters: null,
  60028. maxSimultaneousLights: 0,
  60029. transformFeedbackVaryings: []
  60030. };
  60031. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60032. // Random data
  60033. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60034. var d = [];
  60035. for (var i = 0; i < maxTextureSize; ++i) {
  60036. d.push(Math.random());
  60037. d.push(Math.random());
  60038. d.push(Math.random());
  60039. d.push(Math.random());
  60040. }
  60041. _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);
  60042. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60043. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60044. d = [];
  60045. for (var i = 0; i < maxTextureSize; ++i) {
  60046. d.push(Math.random());
  60047. d.push(Math.random());
  60048. d.push(Math.random());
  60049. d.push(Math.random());
  60050. }
  60051. _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  60052. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60053. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60054. _this._randomTextureSize = maxTextureSize;
  60055. return _this;
  60056. }
  60057. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60058. /**
  60059. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60060. */
  60061. get: function () {
  60062. if (!BABYLON.Engine.LastCreatedEngine) {
  60063. return false;
  60064. }
  60065. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60066. },
  60067. enumerable: true,
  60068. configurable: true
  60069. });
  60070. /**
  60071. * Gets the maximum number of particles active at the same time.
  60072. * @returns The max number of active particles.
  60073. */
  60074. GPUParticleSystem.prototype.getCapacity = function () {
  60075. return this._capacity;
  60076. };
  60077. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60078. /**
  60079. * Gets or set the number of active particles
  60080. */
  60081. get: function () {
  60082. return this._activeCount;
  60083. },
  60084. set: function (value) {
  60085. this._activeCount = Math.min(value, this._capacity);
  60086. },
  60087. enumerable: true,
  60088. configurable: true
  60089. });
  60090. /**
  60091. * Is this system ready to be used/rendered
  60092. * @return true if the system is ready
  60093. */
  60094. GPUParticleSystem.prototype.isReady = function () {
  60095. if (!this._updateEffect) {
  60096. this._recreateUpdateEffect();
  60097. this._recreateRenderEffect();
  60098. return false;
  60099. }
  60100. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60101. return false;
  60102. }
  60103. return true;
  60104. };
  60105. /**
  60106. * Gets Wether the system has been started.
  60107. * @returns True if it has been started, otherwise false.
  60108. */
  60109. GPUParticleSystem.prototype.isStarted = function () {
  60110. return this._started;
  60111. };
  60112. /**
  60113. * Starts the particle system and begins to emit
  60114. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60115. */
  60116. GPUParticleSystem.prototype.start = function (delay) {
  60117. var _this = this;
  60118. if (delay === void 0) { delay = 0; }
  60119. if (delay) {
  60120. setTimeout(function () {
  60121. _this.start(0);
  60122. }, delay);
  60123. return;
  60124. }
  60125. this._started = true;
  60126. this._stopped = false;
  60127. this._preWarmDone = false;
  60128. };
  60129. /**
  60130. * Stops the particle system.
  60131. */
  60132. GPUParticleSystem.prototype.stop = function () {
  60133. this._stopped = true;
  60134. };
  60135. /**
  60136. * Remove all active particles
  60137. */
  60138. GPUParticleSystem.prototype.reset = function () {
  60139. this._releaseBuffers();
  60140. this._releaseVAOs();
  60141. this._currentActiveCount = 0;
  60142. this._targetIndex = 0;
  60143. };
  60144. /**
  60145. * Returns the string "GPUParticleSystem"
  60146. * @returns a string containing the class name
  60147. */
  60148. GPUParticleSystem.prototype.getClassName = function () {
  60149. return "GPUParticleSystem";
  60150. };
  60151. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60152. if (!gradients) {
  60153. return this;
  60154. }
  60155. var index = 0;
  60156. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60157. var valueGradient = gradients_1[_i];
  60158. if (valueGradient.gradient === gradient) {
  60159. gradients.splice(index, 1);
  60160. break;
  60161. }
  60162. index++;
  60163. }
  60164. if (texture) {
  60165. texture.dispose();
  60166. }
  60167. this._releaseBuffers();
  60168. return this;
  60169. };
  60170. /**
  60171. * Adds a new color gradient
  60172. * @param gradient defines the gradient to use (between 0 and 1)
  60173. * @param color defines the color to affect to the specified gradient
  60174. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60175. * @returns the current particle system
  60176. */
  60177. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60178. if (!this._colorGradients) {
  60179. this._colorGradients = [];
  60180. }
  60181. var colorGradient = new BABYLON.ColorGradient();
  60182. colorGradient.gradient = gradient;
  60183. colorGradient.color1 = color1;
  60184. this._colorGradients.push(colorGradient);
  60185. this._colorGradients.sort(function (a, b) {
  60186. if (a.gradient < b.gradient) {
  60187. return -1;
  60188. }
  60189. else if (a.gradient > b.gradient) {
  60190. return 1;
  60191. }
  60192. return 0;
  60193. });
  60194. if (this._colorGradientsTexture) {
  60195. this._colorGradientsTexture.dispose();
  60196. this._colorGradientsTexture = null;
  60197. }
  60198. this._releaseBuffers();
  60199. return this;
  60200. };
  60201. /**
  60202. * Remove a specific color gradient
  60203. * @param gradient defines the gradient to remove
  60204. * @returns the current particle system
  60205. */
  60206. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  60207. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  60208. this._colorGradientsTexture = null;
  60209. return this;
  60210. };
  60211. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  60212. var valueGradient = new BABYLON.FactorGradient();
  60213. valueGradient.gradient = gradient;
  60214. valueGradient.factor1 = factor;
  60215. factorGradients.push(valueGradient);
  60216. factorGradients.sort(function (a, b) {
  60217. if (a.gradient < b.gradient) {
  60218. return -1;
  60219. }
  60220. else if (a.gradient > b.gradient) {
  60221. return 1;
  60222. }
  60223. return 0;
  60224. });
  60225. this._releaseBuffers();
  60226. };
  60227. /**
  60228. * Adds a new size gradient
  60229. * @param gradient defines the gradient to use (between 0 and 1)
  60230. * @param factor defines the size factor to affect to the specified gradient
  60231. * @returns the current particle system
  60232. */
  60233. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  60234. if (!this._sizeGradients) {
  60235. this._sizeGradients = [];
  60236. }
  60237. this._addFactorGradient(this._sizeGradients, gradient, factor);
  60238. if (this._sizeGradientsTexture) {
  60239. this._sizeGradientsTexture.dispose();
  60240. this._sizeGradientsTexture = null;
  60241. }
  60242. this._releaseBuffers();
  60243. return this;
  60244. };
  60245. /**
  60246. * Remove a specific size gradient
  60247. * @param gradient defines the gradient to remove
  60248. * @returns the current particle system
  60249. */
  60250. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60251. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  60252. this._sizeGradientsTexture = null;
  60253. return this;
  60254. };
  60255. /**
  60256. * Adds a new angular speed gradient
  60257. * @param gradient defines the gradient to use (between 0 and 1)
  60258. * @param factor defines the size factor to affect to the specified gradient
  60259. * @returns the current particle system
  60260. */
  60261. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  60262. if (!this._angularSpeedGradients) {
  60263. this._angularSpeedGradients = [];
  60264. }
  60265. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  60266. if (this._angularSpeedGradientsTexture) {
  60267. this._angularSpeedGradientsTexture.dispose();
  60268. this._angularSpeedGradientsTexture = null;
  60269. }
  60270. this._releaseBuffers();
  60271. return this;
  60272. };
  60273. /**
  60274. * Remove a specific angular speed gradient
  60275. * @param gradient defines the gradient to remove
  60276. * @returns the current particle system
  60277. */
  60278. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60279. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  60280. this._angularSpeedGradientsTexture = null;
  60281. return this;
  60282. };
  60283. /**
  60284. * Adds a new velocity gradient
  60285. * @param gradient defines the gradient to use (between 0 and 1)
  60286. * @param factor defines the size factor to affect to the specified gradient
  60287. * @returns the current particle system
  60288. */
  60289. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  60290. if (!this._velocityGradients) {
  60291. this._velocityGradients = [];
  60292. }
  60293. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60294. if (this._velocityGradientsTexture) {
  60295. this._velocityGradientsTexture.dispose();
  60296. this._velocityGradientsTexture = null;
  60297. }
  60298. this._releaseBuffers();
  60299. return this;
  60300. };
  60301. /**
  60302. * Remove a specific velocity gradient
  60303. * @param gradient defines the gradient to remove
  60304. * @returns the current particle system
  60305. */
  60306. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60307. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60308. this._velocityGradientsTexture = null;
  60309. return this;
  60310. };
  60311. GPUParticleSystem.prototype._reset = function () {
  60312. this._releaseBuffers();
  60313. };
  60314. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60315. var updateVertexBuffers = {};
  60316. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60317. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60318. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60319. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60320. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60321. var offset = 12;
  60322. if (!this._colorGradientsTexture) {
  60323. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60324. offset += 4;
  60325. }
  60326. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60327. offset += 3;
  60328. if (!this._isBillboardBased) {
  60329. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60330. offset += 3;
  60331. }
  60332. if (this._angularSpeedGradientsTexture) {
  60333. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60334. offset += 1;
  60335. }
  60336. else {
  60337. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60338. offset += 2;
  60339. }
  60340. if (this._isAnimationSheetEnabled) {
  60341. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60342. offset += 1;
  60343. }
  60344. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60345. this._engine.bindArrayBuffer(null);
  60346. return vao;
  60347. };
  60348. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60349. var renderVertexBuffers = {};
  60350. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60351. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60352. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60353. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60354. var offset = 12;
  60355. if (!this._colorGradientsTexture) {
  60356. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60357. offset += 4;
  60358. }
  60359. offset += 3; // Direction
  60360. if (!this._isBillboardBased) {
  60361. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60362. offset += 3;
  60363. }
  60364. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60365. if (this._angularSpeedGradientsTexture) {
  60366. offset++;
  60367. }
  60368. else {
  60369. offset += 2;
  60370. }
  60371. if (this._isAnimationSheetEnabled) {
  60372. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60373. offset += 1;
  60374. }
  60375. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60376. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60377. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60378. this._engine.bindArrayBuffer(null);
  60379. return vao;
  60380. };
  60381. GPUParticleSystem.prototype._initialize = function (force) {
  60382. if (force === void 0) { force = false; }
  60383. if (this._buffer0 && !force) {
  60384. return;
  60385. }
  60386. var engine = this._scene.getEngine();
  60387. var data = new Array();
  60388. if (!this.isBillboardBased) {
  60389. this._attributesStrideSize += 3;
  60390. }
  60391. if (this._colorGradientsTexture) {
  60392. this._attributesStrideSize -= 4;
  60393. }
  60394. if (this._angularSpeedGradientsTexture) {
  60395. this._attributesStrideSize -= 1;
  60396. }
  60397. if (this._isAnimationSheetEnabled) {
  60398. this._attributesStrideSize += 1;
  60399. }
  60400. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60401. // position
  60402. data.push(0.0);
  60403. data.push(0.0);
  60404. data.push(0.0);
  60405. // Age and life
  60406. data.push(0.0); // create the particle as a dead one to create a new one at start
  60407. data.push(0.0);
  60408. // Seed
  60409. data.push(Math.random());
  60410. data.push(Math.random());
  60411. data.push(Math.random());
  60412. data.push(Math.random());
  60413. // Size
  60414. data.push(0.0);
  60415. data.push(0.0);
  60416. data.push(0.0);
  60417. if (!this._colorGradientsTexture) {
  60418. // color
  60419. data.push(0.0);
  60420. data.push(0.0);
  60421. data.push(0.0);
  60422. data.push(0.0);
  60423. }
  60424. // direction
  60425. data.push(0.0);
  60426. data.push(0.0);
  60427. data.push(0.0);
  60428. if (!this.isBillboardBased) {
  60429. // initialDirection
  60430. data.push(0.0);
  60431. data.push(0.0);
  60432. data.push(0.0);
  60433. }
  60434. // angle
  60435. data.push(0.0);
  60436. if (!this._angularSpeedGradientsTexture) {
  60437. data.push(0.0);
  60438. }
  60439. if (this._isAnimationSheetEnabled) {
  60440. data.push(0.0);
  60441. }
  60442. }
  60443. // Sprite data
  60444. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60445. -0.5, 0.5, 0, 1,
  60446. -0.5, -0.5, 0, 0,
  60447. 0.5, -0.5, 1, 0]);
  60448. // Buffers
  60449. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60450. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60451. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60452. // Update VAO
  60453. this._updateVAO = [];
  60454. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60455. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60456. // Render VAO
  60457. this._renderVAO = [];
  60458. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60459. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60460. // Links
  60461. this._sourceBuffer = this._buffer0;
  60462. this._targetBuffer = this._buffer1;
  60463. };
  60464. /** @hidden */
  60465. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60466. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60467. if (this._isBillboardBased) {
  60468. defines += "\n#define BILLBOARD";
  60469. }
  60470. if (this._colorGradientsTexture) {
  60471. defines += "\n#define COLORGRADIENTS";
  60472. }
  60473. if (this._sizeGradientsTexture) {
  60474. defines += "\n#define SIZEGRADIENTS";
  60475. }
  60476. if (this._angularSpeedGradientsTexture) {
  60477. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60478. }
  60479. if (this._velocityGradientsTexture) {
  60480. defines += "\n#define VELOCITYGRADIENTS";
  60481. }
  60482. if (this.isAnimationSheetEnabled) {
  60483. defines += "\n#define ANIMATESHEET";
  60484. }
  60485. if (this.noiseTexture) {
  60486. defines += "\n#define NOISE";
  60487. }
  60488. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60489. return;
  60490. }
  60491. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60492. if (!this._colorGradientsTexture) {
  60493. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60494. }
  60495. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60496. if (!this._isBillboardBased) {
  60497. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60498. }
  60499. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60500. if (this.isAnimationSheetEnabled) {
  60501. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60502. }
  60503. this._updateEffectOptions.defines = defines;
  60504. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60505. };
  60506. /** @hidden */
  60507. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60508. var defines = "";
  60509. if (this._scene.clipPlane) {
  60510. defines = "\n#define CLIPPLANE";
  60511. }
  60512. if (this._isBillboardBased) {
  60513. defines += "\n#define BILLBOARD";
  60514. switch (this.billboardMode) {
  60515. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60516. defines += "\n#define BILLBOARDY";
  60517. break;
  60518. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60519. default:
  60520. break;
  60521. }
  60522. }
  60523. if (this._colorGradientsTexture) {
  60524. defines += "\n#define COLORGRADIENTS";
  60525. }
  60526. if (this.isAnimationSheetEnabled) {
  60527. defines += "\n#define ANIMATESHEET";
  60528. }
  60529. if (this._renderEffect && this._renderEffect.defines === defines) {
  60530. return;
  60531. }
  60532. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  60533. };
  60534. /**
  60535. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60536. * @param preWarm defines if we are in the pre-warmimg phase
  60537. */
  60538. GPUParticleSystem.prototype.animate = function (preWarm) {
  60539. if (preWarm === void 0) { preWarm = false; }
  60540. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60541. this._actualFrame += this._timeDelta;
  60542. if (!this._stopped) {
  60543. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60544. this.stop();
  60545. }
  60546. }
  60547. };
  60548. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60549. var texture = this[textureName];
  60550. if (!factorGradients || !factorGradients.length || texture) {
  60551. return;
  60552. }
  60553. var data = new Float32Array(this._rawTextureWidth);
  60554. for (var x = 0; x < this._rawTextureWidth; x++) {
  60555. var ratio = x / this._rawTextureWidth;
  60556. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60557. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60558. });
  60559. }
  60560. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60561. };
  60562. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60563. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60564. };
  60565. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60566. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60567. };
  60568. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60569. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60570. };
  60571. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60572. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60573. return;
  60574. }
  60575. var data = new Uint8Array(this._rawTextureWidth * 4);
  60576. var tmpColor = BABYLON.Tmp.Color4[0];
  60577. for (var x = 0; x < this._rawTextureWidth; x++) {
  60578. var ratio = x / this._rawTextureWidth;
  60579. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60580. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60581. data[x * 4] = tmpColor.r * 255;
  60582. data[x * 4 + 1] = tmpColor.g * 255;
  60583. data[x * 4 + 2] = tmpColor.b * 255;
  60584. data[x * 4 + 3] = tmpColor.a * 255;
  60585. });
  60586. }
  60587. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60588. };
  60589. /**
  60590. * Renders the particle system in its current state
  60591. * @param preWarm defines if the system should only update the particles but not render them
  60592. * @returns the current number of particles
  60593. */
  60594. GPUParticleSystem.prototype.render = function (preWarm) {
  60595. if (preWarm === void 0) { preWarm = false; }
  60596. if (!this._started) {
  60597. return 0;
  60598. }
  60599. this._createColorGradientTexture();
  60600. this._createSizeGradientTexture();
  60601. this._createAngularSpeedGradientTexture();
  60602. this._createVelocityGradientTexture();
  60603. this._recreateUpdateEffect();
  60604. this._recreateRenderEffect();
  60605. if (!this.isReady()) {
  60606. return 0;
  60607. }
  60608. if (!preWarm) {
  60609. if (!this._preWarmDone && this.preWarmCycles) {
  60610. for (var index = 0; index < this.preWarmCycles; index++) {
  60611. this.animate(true);
  60612. this.render(true);
  60613. }
  60614. this._preWarmDone = true;
  60615. }
  60616. if (this._currentRenderId === this._scene.getRenderId()) {
  60617. return 0;
  60618. }
  60619. this._currentRenderId = this._scene.getRenderId();
  60620. }
  60621. // Get everything ready to render
  60622. this._initialize();
  60623. this._accumulatedCount += this.emitRate * this._timeDelta;
  60624. if (this._accumulatedCount > 1) {
  60625. var intPart = this._accumulatedCount | 0;
  60626. this._accumulatedCount -= intPart;
  60627. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60628. }
  60629. if (!this._currentActiveCount) {
  60630. return 0;
  60631. }
  60632. // Enable update effect
  60633. this._engine.enableEffect(this._updateEffect);
  60634. this._engine.setState(false);
  60635. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60636. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60637. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60638. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60639. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60640. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60641. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60642. if (!this._colorGradientsTexture) {
  60643. this._updateEffect.setDirectColor4("color1", this.color1);
  60644. this._updateEffect.setDirectColor4("color2", this.color2);
  60645. }
  60646. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60647. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60648. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60649. this._updateEffect.setVector3("gravity", this.gravity);
  60650. if (this._sizeGradientsTexture) {
  60651. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60652. }
  60653. if (this._angularSpeedGradientsTexture) {
  60654. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60655. }
  60656. if (this._velocityGradientsTexture) {
  60657. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60658. }
  60659. if (this.particleEmitterType) {
  60660. this.particleEmitterType.applyToShader(this._updateEffect);
  60661. }
  60662. if (this._isAnimationSheetEnabled) {
  60663. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60664. }
  60665. if (this.noiseTexture) {
  60666. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  60667. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  60668. }
  60669. var emitterWM;
  60670. if (this.emitter.position) {
  60671. var emitterMesh = this.emitter;
  60672. emitterWM = emitterMesh.getWorldMatrix();
  60673. }
  60674. else {
  60675. var emitterPosition = this.emitter;
  60676. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60677. }
  60678. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60679. // Bind source VAO
  60680. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60681. // Update
  60682. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60683. this._engine.setRasterizerState(false);
  60684. this._engine.beginTransformFeedback(true);
  60685. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60686. this._engine.endTransformFeedback();
  60687. this._engine.setRasterizerState(true);
  60688. this._engine.bindTransformFeedbackBuffer(null);
  60689. if (!preWarm) {
  60690. // Enable render effect
  60691. this._engine.enableEffect(this._renderEffect);
  60692. var viewMatrix = this._scene.getViewMatrix();
  60693. this._renderEffect.setMatrix("view", viewMatrix);
  60694. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60695. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60696. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60697. if (this._colorGradientsTexture) {
  60698. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60699. }
  60700. else {
  60701. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60702. }
  60703. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60704. var baseSize = this.particleTexture.getBaseSize();
  60705. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60706. }
  60707. if (this._isBillboardBased) {
  60708. var camera = this._scene.activeCamera;
  60709. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60710. }
  60711. if (this._scene.clipPlane) {
  60712. var clipPlane = this._scene.clipPlane;
  60713. var invView = viewMatrix.clone();
  60714. invView.invert();
  60715. this._renderEffect.setMatrix("invView", invView);
  60716. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60717. }
  60718. // Draw order
  60719. switch (this.blendMode) {
  60720. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60721. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60722. break;
  60723. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60724. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60725. break;
  60726. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60727. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60728. break;
  60729. }
  60730. if (this.forceDepthWrite) {
  60731. this._engine.setDepthWrite(true);
  60732. }
  60733. // Bind source VAO
  60734. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60735. // Render
  60736. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60737. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60738. }
  60739. // Switch VAOs
  60740. this._targetIndex++;
  60741. if (this._targetIndex === 2) {
  60742. this._targetIndex = 0;
  60743. }
  60744. // Switch buffers
  60745. var tmpBuffer = this._sourceBuffer;
  60746. this._sourceBuffer = this._targetBuffer;
  60747. this._targetBuffer = tmpBuffer;
  60748. return this._currentActiveCount;
  60749. };
  60750. /**
  60751. * Rebuilds the particle system
  60752. */
  60753. GPUParticleSystem.prototype.rebuild = function () {
  60754. this._initialize(true);
  60755. };
  60756. GPUParticleSystem.prototype._releaseBuffers = function () {
  60757. if (this._buffer0) {
  60758. this._buffer0.dispose();
  60759. this._buffer0 = null;
  60760. }
  60761. if (this._buffer1) {
  60762. this._buffer1.dispose();
  60763. this._buffer1 = null;
  60764. }
  60765. if (this._spriteBuffer) {
  60766. this._spriteBuffer.dispose();
  60767. this._spriteBuffer = null;
  60768. }
  60769. };
  60770. GPUParticleSystem.prototype._releaseVAOs = function () {
  60771. if (!this._updateVAO) {
  60772. return;
  60773. }
  60774. for (var index = 0; index < this._updateVAO.length; index++) {
  60775. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60776. }
  60777. this._updateVAO = [];
  60778. for (var index = 0; index < this._renderVAO.length; index++) {
  60779. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60780. }
  60781. this._renderVAO = [];
  60782. };
  60783. /**
  60784. * Disposes the particle system and free the associated resources
  60785. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60786. */
  60787. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60788. if (disposeTexture === void 0) { disposeTexture = true; }
  60789. var index = this._scene.particleSystems.indexOf(this);
  60790. if (index > -1) {
  60791. this._scene.particleSystems.splice(index, 1);
  60792. }
  60793. this._releaseBuffers();
  60794. this._releaseVAOs();
  60795. if (this._colorGradientsTexture) {
  60796. this._colorGradientsTexture.dispose();
  60797. this._colorGradientsTexture = null;
  60798. }
  60799. if (this._sizeGradientsTexture) {
  60800. this._sizeGradientsTexture.dispose();
  60801. this._sizeGradientsTexture = null;
  60802. }
  60803. if (this._angularSpeedGradientsTexture) {
  60804. this._angularSpeedGradientsTexture.dispose();
  60805. this._angularSpeedGradientsTexture = null;
  60806. }
  60807. if (this._velocityGradientsTexture) {
  60808. this._velocityGradientsTexture.dispose();
  60809. this._velocityGradientsTexture = null;
  60810. }
  60811. if (this._randomTexture) {
  60812. this._randomTexture.dispose();
  60813. this._randomTexture = null;
  60814. }
  60815. if (this._randomTexture2) {
  60816. this._randomTexture2.dispose();
  60817. this._randomTexture2 = null;
  60818. }
  60819. if (disposeTexture && this.particleTexture) {
  60820. this.particleTexture.dispose();
  60821. this.particleTexture = null;
  60822. }
  60823. if (disposeTexture && this.noiseTexture) {
  60824. this.noiseTexture.dispose();
  60825. this.noiseTexture = null;
  60826. }
  60827. // Callback
  60828. this.onDisposeObservable.notifyObservers(this);
  60829. this.onDisposeObservable.clear();
  60830. };
  60831. /**
  60832. * Clones the particle system.
  60833. * @param name The name of the cloned object
  60834. * @param newEmitter The new emitter to use
  60835. * @returns the cloned particle system
  60836. */
  60837. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60838. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60839. BABYLON.Tools.DeepCopy(this, result);
  60840. if (newEmitter === undefined) {
  60841. newEmitter = this.emitter;
  60842. }
  60843. result.emitter = newEmitter;
  60844. if (this.particleTexture) {
  60845. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60846. }
  60847. return result;
  60848. };
  60849. /**
  60850. * Serializes the particle system to a JSON object.
  60851. * @returns the JSON object
  60852. */
  60853. GPUParticleSystem.prototype.serialize = function () {
  60854. var serializationObject = {};
  60855. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60856. serializationObject.activeParticleCount = this.activeParticleCount;
  60857. return serializationObject;
  60858. };
  60859. /**
  60860. * Parses a JSON object to create a GPU particle system.
  60861. * @param parsedParticleSystem The JSON object to parse
  60862. * @param scene The scene to create the particle system in
  60863. * @param rootUrl The root url to use to load external dependencies like texture
  60864. * @returns the parsed GPU particle system
  60865. */
  60866. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  60867. var name = parsedParticleSystem.name;
  60868. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  60869. if (parsedParticleSystem.activeParticleCount) {
  60870. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  60871. }
  60872. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60873. return particleSystem;
  60874. };
  60875. return GPUParticleSystem;
  60876. }(BABYLON.BaseParticleSystem));
  60877. BABYLON.GPUParticleSystem = GPUParticleSystem;
  60878. })(BABYLON || (BABYLON = {}));
  60879. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  60880. var BABYLON;
  60881. (function (BABYLON) {
  60882. /**
  60883. * Represents one particle of a solid particle system.
  60884. */
  60885. var SolidParticle = /** @class */ (function () {
  60886. /**
  60887. * Creates a Solid Particle object.
  60888. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  60889. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  60890. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  60891. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  60892. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  60893. * @param shapeId (integer) is the model shape identifier in the SPS.
  60894. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  60895. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  60896. */
  60897. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  60898. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  60899. /**
  60900. * particle global index
  60901. */
  60902. this.idx = 0;
  60903. /**
  60904. * The color of the particle
  60905. */
  60906. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60907. /**
  60908. * The world space position of the particle.
  60909. */
  60910. this.position = BABYLON.Vector3.Zero();
  60911. /**
  60912. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  60913. */
  60914. this.rotation = BABYLON.Vector3.Zero();
  60915. /**
  60916. * The scaling of the particle.
  60917. */
  60918. this.scaling = BABYLON.Vector3.One();
  60919. /**
  60920. * The uvs of the particle.
  60921. */
  60922. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  60923. /**
  60924. * The current speed of the particle.
  60925. */
  60926. this.velocity = BABYLON.Vector3.Zero();
  60927. /**
  60928. * The pivot point in the particle local space.
  60929. */
  60930. this.pivot = BABYLON.Vector3.Zero();
  60931. /**
  60932. * Must the particle be translated from its pivot point in its local space ?
  60933. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  60934. * Default : false
  60935. */
  60936. this.translateFromPivot = false;
  60937. /**
  60938. * Is the particle active or not ?
  60939. */
  60940. this.alive = true;
  60941. /**
  60942. * Is the particle visible or not ?
  60943. */
  60944. this.isVisible = true;
  60945. /**
  60946. * Index of this particle in the global "positions" array (Internal use)
  60947. */
  60948. this._pos = 0;
  60949. /**
  60950. * Index of this particle in the global "indices" array (Internal use)
  60951. */
  60952. this._ind = 0;
  60953. /**
  60954. * ModelShape id of this particle
  60955. */
  60956. this.shapeId = 0;
  60957. /**
  60958. * Index of the particle in its shape id (Internal use)
  60959. */
  60960. this.idxInShape = 0;
  60961. /**
  60962. * Still set as invisible in order to skip useless computations (Internal use)
  60963. */
  60964. this._stillInvisible = false;
  60965. /**
  60966. * Last computed particle rotation matrix
  60967. */
  60968. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  60969. /**
  60970. * Parent particle Id, if any.
  60971. * Default null.
  60972. */
  60973. this.parentId = null;
  60974. /**
  60975. * Internal global position in the SPS.
  60976. */
  60977. this._globalPosition = BABYLON.Vector3.Zero();
  60978. this.idx = particleIndex;
  60979. this._pos = positionIndex;
  60980. this._ind = indiceIndex;
  60981. this._model = model;
  60982. this.shapeId = shapeId;
  60983. this.idxInShape = idxInShape;
  60984. this._sps = sps;
  60985. if (modelBoundingInfo) {
  60986. this._modelBoundingInfo = modelBoundingInfo;
  60987. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  60988. }
  60989. }
  60990. Object.defineProperty(SolidParticle.prototype, "scale", {
  60991. /**
  60992. * Legacy support, changed scale to scaling
  60993. */
  60994. get: function () {
  60995. return this.scaling;
  60996. },
  60997. /**
  60998. * Legacy support, changed scale to scaling
  60999. */
  61000. set: function (scale) {
  61001. this.scaling = scale;
  61002. },
  61003. enumerable: true,
  61004. configurable: true
  61005. });
  61006. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61007. /**
  61008. * Legacy support, changed quaternion to rotationQuaternion
  61009. */
  61010. get: function () {
  61011. return this.rotationQuaternion;
  61012. },
  61013. /**
  61014. * Legacy support, changed quaternion to rotationQuaternion
  61015. */
  61016. set: function (q) {
  61017. this.rotationQuaternion = q;
  61018. },
  61019. enumerable: true,
  61020. configurable: true
  61021. });
  61022. /**
  61023. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61024. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61025. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61026. * @returns true if it intersects
  61027. */
  61028. SolidParticle.prototype.intersectsMesh = function (target) {
  61029. if (!this._boundingInfo || !target._boundingInfo) {
  61030. return false;
  61031. }
  61032. if (this._sps._bSphereOnly) {
  61033. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61034. }
  61035. return this._boundingInfo.intersects(target._boundingInfo, false);
  61036. };
  61037. return SolidParticle;
  61038. }());
  61039. BABYLON.SolidParticle = SolidParticle;
  61040. /**
  61041. * Represents the shape of the model used by one particle of a solid particle system.
  61042. * SPS internal tool, don't use it manually.
  61043. */
  61044. var ModelShape = /** @class */ (function () {
  61045. /**
  61046. * 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.
  61047. * SPS internal tool, don't use it manually.
  61048. * @hidden
  61049. */
  61050. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61051. /**
  61052. * length of the shape in the model indices array (internal use)
  61053. */
  61054. this._indicesLength = 0;
  61055. this.shapeID = id;
  61056. this._shape = shape;
  61057. this._indicesLength = indicesLength;
  61058. this._shapeUV = shapeUV;
  61059. this._positionFunction = posFunction;
  61060. this._vertexFunction = vtxFunction;
  61061. }
  61062. return ModelShape;
  61063. }());
  61064. BABYLON.ModelShape = ModelShape;
  61065. /**
  61066. * Represents a Depth Sorted Particle in the solid particle system.
  61067. */
  61068. var DepthSortedParticle = /** @class */ (function () {
  61069. function DepthSortedParticle() {
  61070. /**
  61071. * Index of the particle in the "indices" array
  61072. */
  61073. this.ind = 0;
  61074. /**
  61075. * Length of the particle shape in the "indices" array
  61076. */
  61077. this.indicesLength = 0;
  61078. /**
  61079. * Squared distance from the particle to the camera
  61080. */
  61081. this.sqDistance = 0.0;
  61082. }
  61083. return DepthSortedParticle;
  61084. }());
  61085. BABYLON.DepthSortedParticle = DepthSortedParticle;
  61086. })(BABYLON || (BABYLON = {}));
  61087. //# sourceMappingURL=babylon.solidParticle.js.map
  61088. var BABYLON;
  61089. (function (BABYLON) {
  61090. /**
  61091. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  61092. *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.
  61093. * The SPS is also a particle system. It provides some methods to manage the particles.
  61094. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  61095. *
  61096. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  61097. */
  61098. var SolidParticleSystem = /** @class */ (function () {
  61099. /**
  61100. * Creates a SPS (Solid Particle System) object.
  61101. * @param name (String) is the SPS name, this will be the underlying mesh name.
  61102. * @param scene (Scene) is the scene in which the SPS is added.
  61103. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  61104. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  61105. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  61106. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  61107. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  61108. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  61109. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  61110. */
  61111. function SolidParticleSystem(name, scene, options) {
  61112. /**
  61113. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  61114. * Example : var p = SPS.particles[i];
  61115. */
  61116. this.particles = new Array();
  61117. /**
  61118. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  61119. */
  61120. this.nbParticles = 0;
  61121. /**
  61122. * If the particles must ever face the camera (default false). Useful for planar particles.
  61123. */
  61124. this.billboard = false;
  61125. /**
  61126. * Recompute normals when adding a shape
  61127. */
  61128. this.recomputeNormals = true;
  61129. /**
  61130. * This a counter ofr your own usage. It's not set by any SPS functions.
  61131. */
  61132. this.counter = 0;
  61133. /**
  61134. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  61135. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  61136. */
  61137. this.vars = {};
  61138. /**
  61139. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  61140. */
  61141. this._bSphereOnly = false;
  61142. /**
  61143. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  61144. */
  61145. this._bSphereRadiusFactor = 1.0;
  61146. this._positions = new Array();
  61147. this._indices = new Array();
  61148. this._normals = new Array();
  61149. this._colors = new Array();
  61150. this._uvs = new Array();
  61151. this._index = 0; // indices index
  61152. this._updatable = true;
  61153. this._pickable = false;
  61154. this._isVisibilityBoxLocked = false;
  61155. this._alwaysVisible = false;
  61156. this._depthSort = false;
  61157. this._shapeCounter = 0;
  61158. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  61159. this._color = new BABYLON.Color4(0, 0, 0, 0);
  61160. this._computeParticleColor = true;
  61161. this._computeParticleTexture = true;
  61162. this._computeParticleRotation = true;
  61163. this._computeParticleVertex = false;
  61164. this._computeBoundingBox = false;
  61165. this._depthSortParticles = true;
  61166. this._cam_axisZ = BABYLON.Vector3.Zero();
  61167. this._cam_axisY = BABYLON.Vector3.Zero();
  61168. this._cam_axisX = BABYLON.Vector3.Zero();
  61169. this._axisZ = BABYLON.Axis.Z;
  61170. this._camDir = BABYLON.Vector3.Zero();
  61171. this._camInvertedPosition = BABYLON.Vector3.Zero();
  61172. this._rotMatrix = new BABYLON.Matrix();
  61173. this._invertMatrix = new BABYLON.Matrix();
  61174. this._rotated = BABYLON.Vector3.Zero();
  61175. this._quaternion = new BABYLON.Quaternion();
  61176. this._vertex = BABYLON.Vector3.Zero();
  61177. this._normal = BABYLON.Vector3.Zero();
  61178. this._yaw = 0.0;
  61179. this._pitch = 0.0;
  61180. this._roll = 0.0;
  61181. this._halfroll = 0.0;
  61182. this._halfpitch = 0.0;
  61183. this._halfyaw = 0.0;
  61184. this._sinRoll = 0.0;
  61185. this._cosRoll = 0.0;
  61186. this._sinPitch = 0.0;
  61187. this._cosPitch = 0.0;
  61188. this._sinYaw = 0.0;
  61189. this._cosYaw = 0.0;
  61190. this._mustUnrotateFixedNormals = false;
  61191. this._minimum = BABYLON.Vector3.Zero();
  61192. this._maximum = BABYLON.Vector3.Zero();
  61193. this._minBbox = BABYLON.Vector3.Zero();
  61194. this._maxBbox = BABYLON.Vector3.Zero();
  61195. this._particlesIntersect = false;
  61196. this._depthSortFunction = function (p1, p2) {
  61197. return (p2.sqDistance - p1.sqDistance);
  61198. };
  61199. this._needs32Bits = false;
  61200. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  61201. this._scaledPivot = BABYLON.Vector3.Zero();
  61202. this._particleHasParent = false;
  61203. this.name = name;
  61204. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61205. this._camera = scene.activeCamera;
  61206. this._pickable = options ? options.isPickable : false;
  61207. this._depthSort = options ? options.enableDepthSort : false;
  61208. this._particlesIntersect = options ? options.particleIntersection : false;
  61209. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  61210. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  61211. if (options && options.updatable !== undefined) {
  61212. this._updatable = options.updatable;
  61213. }
  61214. else {
  61215. this._updatable = true;
  61216. }
  61217. if (this._pickable) {
  61218. this.pickedParticles = [];
  61219. }
  61220. if (this._depthSort) {
  61221. this.depthSortedParticles = [];
  61222. }
  61223. }
  61224. /**
  61225. * Builds the SPS underlying mesh. Returns a standard Mesh.
  61226. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  61227. * @returns the created mesh
  61228. */
  61229. SolidParticleSystem.prototype.buildMesh = function () {
  61230. if (this.nbParticles === 0) {
  61231. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  61232. this.addShape(triangle, 1);
  61233. triangle.dispose();
  61234. }
  61235. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  61236. this._positions32 = new Float32Array(this._positions);
  61237. this._uvs32 = new Float32Array(this._uvs);
  61238. this._colors32 = new Float32Array(this._colors);
  61239. if (this.recomputeNormals) {
  61240. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  61241. }
  61242. this._normals32 = new Float32Array(this._normals);
  61243. this._fixedNormal32 = new Float32Array(this._normals);
  61244. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  61245. this._unrotateFixedNormals();
  61246. }
  61247. var vertexData = new BABYLON.VertexData();
  61248. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  61249. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  61250. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  61251. if (this._uvs32.length > 0) {
  61252. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  61253. }
  61254. if (this._colors32.length > 0) {
  61255. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  61256. }
  61257. var mesh = new BABYLON.Mesh(this.name, this._scene);
  61258. vertexData.applyToMesh(mesh, this._updatable);
  61259. this.mesh = mesh;
  61260. this.mesh.isPickable = this._pickable;
  61261. // free memory
  61262. if (!this._depthSort) {
  61263. this._indices = null;
  61264. }
  61265. this._positions = null;
  61266. this._normals = null;
  61267. this._uvs = null;
  61268. this._colors = null;
  61269. if (!this._updatable) {
  61270. this.particles.length = 0;
  61271. }
  61272. return mesh;
  61273. };
  61274. /**
  61275. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  61276. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  61277. * Thus the particles generated from `digest()` have their property `position` set yet.
  61278. * @param mesh ( Mesh ) is the mesh to be digested
  61279. * @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
  61280. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  61281. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  61282. * @returns the current SPS
  61283. */
  61284. SolidParticleSystem.prototype.digest = function (mesh, options) {
  61285. var size = (options && options.facetNb) || 1;
  61286. var number = (options && options.number) || 0;
  61287. var delta = (options && options.delta) || 0;
  61288. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61289. var meshInd = mesh.getIndices();
  61290. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61291. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61292. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61293. var f = 0; // facet counter
  61294. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61295. // compute size from number
  61296. if (number) {
  61297. number = (number > totalFacets) ? totalFacets : number;
  61298. size = Math.round(totalFacets / number);
  61299. delta = 0;
  61300. }
  61301. else {
  61302. size = (size > totalFacets) ? totalFacets : size;
  61303. }
  61304. var facetPos = []; // submesh positions
  61305. var facetInd = []; // submesh indices
  61306. var facetUV = []; // submesh UV
  61307. var facetCol = []; // submesh colors
  61308. var barycenter = BABYLON.Vector3.Zero();
  61309. var sizeO = size;
  61310. while (f < totalFacets) {
  61311. size = sizeO + Math.floor((1 + delta) * Math.random());
  61312. if (f > totalFacets - size) {
  61313. size = totalFacets - f;
  61314. }
  61315. // reset temp arrays
  61316. facetPos.length = 0;
  61317. facetInd.length = 0;
  61318. facetUV.length = 0;
  61319. facetCol.length = 0;
  61320. // iterate over "size" facets
  61321. var fi = 0;
  61322. for (var j = f * 3; j < (f + size) * 3; j++) {
  61323. facetInd.push(fi);
  61324. var i = meshInd[j];
  61325. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61326. if (meshUV) {
  61327. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61328. }
  61329. if (meshCol) {
  61330. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61331. }
  61332. fi++;
  61333. }
  61334. // create a model shape for each single particle
  61335. var idx = this.nbParticles;
  61336. var shape = this._posToShape(facetPos);
  61337. var shapeUV = this._uvsToShapeUV(facetUV);
  61338. // compute the barycenter of the shape
  61339. var v;
  61340. for (v = 0; v < shape.length; v++) {
  61341. barycenter.addInPlace(shape[v]);
  61342. }
  61343. barycenter.scaleInPlace(1 / shape.length);
  61344. // shift the shape from its barycenter to the origin
  61345. for (v = 0; v < shape.length; v++) {
  61346. shape[v].subtractInPlace(barycenter);
  61347. }
  61348. var bInfo;
  61349. if (this._particlesIntersect) {
  61350. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61351. }
  61352. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61353. // add the particle in the SPS
  61354. var currentPos = this._positions.length;
  61355. var currentInd = this._indices.length;
  61356. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61357. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61358. // initialize the particle position
  61359. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61360. this._index += shape.length;
  61361. idx++;
  61362. this.nbParticles++;
  61363. this._shapeCounter++;
  61364. f += size;
  61365. }
  61366. return this;
  61367. };
  61368. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61369. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61370. var index = 0;
  61371. var idx = 0;
  61372. for (var p = 0; p < this.particles.length; p++) {
  61373. this._particle = this.particles[p];
  61374. this._shape = this._particle._model._shape;
  61375. if (this._particle.rotationQuaternion) {
  61376. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61377. }
  61378. else {
  61379. this._yaw = this._particle.rotation.y;
  61380. this._pitch = this._particle.rotation.x;
  61381. this._roll = this._particle.rotation.z;
  61382. this._quaternionRotationYPR();
  61383. }
  61384. this._quaternionToRotationMatrix();
  61385. this._rotMatrix.invertToRef(this._invertMatrix);
  61386. for (var pt = 0; pt < this._shape.length; pt++) {
  61387. idx = index + pt * 3;
  61388. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61389. this._fixedNormal32[idx] = this._normal.x;
  61390. this._fixedNormal32[idx + 1] = this._normal.y;
  61391. this._fixedNormal32[idx + 2] = this._normal.z;
  61392. }
  61393. index = idx + 3;
  61394. }
  61395. };
  61396. //reset copy
  61397. SolidParticleSystem.prototype._resetCopy = function () {
  61398. this._copy.position.x = 0;
  61399. this._copy.position.y = 0;
  61400. this._copy.position.z = 0;
  61401. this._copy.rotation.x = 0;
  61402. this._copy.rotation.y = 0;
  61403. this._copy.rotation.z = 0;
  61404. this._copy.rotationQuaternion = null;
  61405. this._copy.scaling.x = 1.0;
  61406. this._copy.scaling.y = 1.0;
  61407. this._copy.scaling.z = 1.0;
  61408. this._copy.uvs.x = 0;
  61409. this._copy.uvs.y = 0;
  61410. this._copy.uvs.z = 1.0;
  61411. this._copy.uvs.w = 1.0;
  61412. this._copy.color = null;
  61413. this._copy.translateFromPivot = false;
  61414. };
  61415. // _meshBuilder : inserts the shape model in the global SPS mesh
  61416. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61417. var i;
  61418. var u = 0;
  61419. var c = 0;
  61420. var n = 0;
  61421. this._resetCopy();
  61422. if (options && options.positionFunction) { // call to custom positionFunction
  61423. options.positionFunction(this._copy, idx, idxInShape);
  61424. this._mustUnrotateFixedNormals = true;
  61425. }
  61426. if (this._copy.rotationQuaternion) {
  61427. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61428. }
  61429. else {
  61430. this._yaw = this._copy.rotation.y;
  61431. this._pitch = this._copy.rotation.x;
  61432. this._roll = this._copy.rotation.z;
  61433. this._quaternionRotationYPR();
  61434. }
  61435. this._quaternionToRotationMatrix();
  61436. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61437. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61438. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61439. if (this._copy.translateFromPivot) {
  61440. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61441. }
  61442. else {
  61443. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61444. }
  61445. for (i = 0; i < shape.length; i++) {
  61446. this._vertex.x = shape[i].x;
  61447. this._vertex.y = shape[i].y;
  61448. this._vertex.z = shape[i].z;
  61449. if (options && options.vertexFunction) {
  61450. options.vertexFunction(this._copy, this._vertex, i);
  61451. }
  61452. this._vertex.x *= this._copy.scaling.x;
  61453. this._vertex.y *= this._copy.scaling.y;
  61454. this._vertex.z *= this._copy.scaling.z;
  61455. this._vertex.x -= this._scaledPivot.x;
  61456. this._vertex.y -= this._scaledPivot.y;
  61457. this._vertex.z -= this._scaledPivot.z;
  61458. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61459. this._rotated.addInPlace(this._pivotBackTranslation);
  61460. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61461. if (meshUV) {
  61462. 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);
  61463. u += 2;
  61464. }
  61465. if (this._copy.color) {
  61466. this._color = this._copy.color;
  61467. }
  61468. else if (meshCol && meshCol[c] !== undefined) {
  61469. this._color.r = meshCol[c];
  61470. this._color.g = meshCol[c + 1];
  61471. this._color.b = meshCol[c + 2];
  61472. this._color.a = meshCol[c + 3];
  61473. }
  61474. else {
  61475. this._color.r = 1.0;
  61476. this._color.g = 1.0;
  61477. this._color.b = 1.0;
  61478. this._color.a = 1.0;
  61479. }
  61480. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61481. c += 4;
  61482. if (!this.recomputeNormals && meshNor) {
  61483. this._normal.x = meshNor[n];
  61484. this._normal.y = meshNor[n + 1];
  61485. this._normal.z = meshNor[n + 2];
  61486. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61487. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61488. n += 3;
  61489. }
  61490. }
  61491. for (i = 0; i < meshInd.length; i++) {
  61492. var current_ind = p + meshInd[i];
  61493. indices.push(current_ind);
  61494. if (current_ind > 65535) {
  61495. this._needs32Bits = true;
  61496. }
  61497. }
  61498. if (this._pickable) {
  61499. var nbfaces = meshInd.length / 3;
  61500. for (i = 0; i < nbfaces; i++) {
  61501. this.pickedParticles.push({ idx: idx, faceId: i });
  61502. }
  61503. }
  61504. if (this._depthSort) {
  61505. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61506. }
  61507. return this._copy;
  61508. };
  61509. // returns a shape array from positions array
  61510. SolidParticleSystem.prototype._posToShape = function (positions) {
  61511. var shape = [];
  61512. for (var i = 0; i < positions.length; i += 3) {
  61513. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61514. }
  61515. return shape;
  61516. };
  61517. // returns a shapeUV array from a Vector4 uvs
  61518. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61519. var shapeUV = [];
  61520. if (uvs) {
  61521. for (var i = 0; i < uvs.length; i++)
  61522. shapeUV.push(uvs[i]);
  61523. }
  61524. return shapeUV;
  61525. };
  61526. // adds a new particle object in the particles array
  61527. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61528. if (bInfo === void 0) { bInfo = null; }
  61529. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61530. this.particles.push(sp);
  61531. return sp;
  61532. };
  61533. /**
  61534. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61535. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61536. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61537. * @param nb (positive integer) the number of particles to be created from this model
  61538. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61539. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61540. * @returns the number of shapes in the system
  61541. */
  61542. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61543. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61544. var meshInd = mesh.getIndices();
  61545. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61546. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61547. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61548. var bbInfo;
  61549. if (this._particlesIntersect) {
  61550. bbInfo = mesh.getBoundingInfo();
  61551. }
  61552. var shape = this._posToShape(meshPos);
  61553. var shapeUV = this._uvsToShapeUV(meshUV);
  61554. var posfunc = options ? options.positionFunction : null;
  61555. var vtxfunc = options ? options.vertexFunction : null;
  61556. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61557. // particles
  61558. var sp;
  61559. var currentCopy;
  61560. var idx = this.nbParticles;
  61561. for (var i = 0; i < nb; i++) {
  61562. var currentPos = this._positions.length;
  61563. var currentInd = this._indices.length;
  61564. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61565. if (this._updatable) {
  61566. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61567. sp.position.copyFrom(currentCopy.position);
  61568. sp.rotation.copyFrom(currentCopy.rotation);
  61569. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61570. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61571. }
  61572. if (currentCopy.color && sp.color) {
  61573. sp.color.copyFrom(currentCopy.color);
  61574. }
  61575. sp.scaling.copyFrom(currentCopy.scaling);
  61576. sp.uvs.copyFrom(currentCopy.uvs);
  61577. }
  61578. this._index += shape.length;
  61579. idx++;
  61580. }
  61581. this.nbParticles += nb;
  61582. this._shapeCounter++;
  61583. return this._shapeCounter - 1;
  61584. };
  61585. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61586. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61587. this._resetCopy();
  61588. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61589. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61590. }
  61591. if (this._copy.rotationQuaternion) {
  61592. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61593. }
  61594. else {
  61595. this._yaw = this._copy.rotation.y;
  61596. this._pitch = this._copy.rotation.x;
  61597. this._roll = this._copy.rotation.z;
  61598. this._quaternionRotationYPR();
  61599. }
  61600. this._quaternionToRotationMatrix();
  61601. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61602. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61603. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61604. if (this._copy.translateFromPivot) {
  61605. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61606. }
  61607. else {
  61608. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61609. }
  61610. this._shape = particle._model._shape;
  61611. for (var pt = 0; pt < this._shape.length; pt++) {
  61612. this._vertex.x = this._shape[pt].x;
  61613. this._vertex.y = this._shape[pt].y;
  61614. this._vertex.z = this._shape[pt].z;
  61615. if (particle._model._vertexFunction) {
  61616. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61617. }
  61618. this._vertex.x *= this._copy.scaling.x;
  61619. this._vertex.y *= this._copy.scaling.y;
  61620. this._vertex.z *= this._copy.scaling.z;
  61621. this._vertex.x -= this._scaledPivot.x;
  61622. this._vertex.y -= this._scaledPivot.y;
  61623. this._vertex.z -= this._scaledPivot.z;
  61624. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61625. this._rotated.addInPlace(this._pivotBackTranslation);
  61626. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61627. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61628. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  61629. }
  61630. particle.position.x = 0.0;
  61631. particle.position.y = 0.0;
  61632. particle.position.z = 0.0;
  61633. particle.rotation.x = 0.0;
  61634. particle.rotation.y = 0.0;
  61635. particle.rotation.z = 0.0;
  61636. particle.rotationQuaternion = null;
  61637. particle.scaling.x = 1.0;
  61638. particle.scaling.y = 1.0;
  61639. particle.scaling.z = 1.0;
  61640. particle.uvs.x = 0.0;
  61641. particle.uvs.y = 0.0;
  61642. particle.uvs.z = 1.0;
  61643. particle.uvs.w = 1.0;
  61644. particle.pivot.x = 0.0;
  61645. particle.pivot.y = 0.0;
  61646. particle.pivot.z = 0.0;
  61647. particle.translateFromPivot = false;
  61648. particle.parentId = null;
  61649. };
  61650. /**
  61651. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61652. * @returns the SPS.
  61653. */
  61654. SolidParticleSystem.prototype.rebuildMesh = function () {
  61655. for (var p = 0; p < this.particles.length; p++) {
  61656. this._rebuildParticle(this.particles[p]);
  61657. }
  61658. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61659. return this;
  61660. };
  61661. /**
  61662. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61663. * This method calls `updateParticle()` for each particle of the SPS.
  61664. * For an animated SPS, it is usually called within the render loop.
  61665. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61666. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61667. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61668. * @returns the SPS.
  61669. */
  61670. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61671. if (start === void 0) { start = 0; }
  61672. if (end === void 0) { end = this.nbParticles - 1; }
  61673. if (update === void 0) { update = true; }
  61674. if (!this._updatable) {
  61675. return this;
  61676. }
  61677. // custom beforeUpdate
  61678. this.beforeUpdateParticles(start, end, update);
  61679. this._cam_axisX.x = 1.0;
  61680. this._cam_axisX.y = 0.0;
  61681. this._cam_axisX.z = 0.0;
  61682. this._cam_axisY.x = 0.0;
  61683. this._cam_axisY.y = 1.0;
  61684. this._cam_axisY.z = 0.0;
  61685. this._cam_axisZ.x = 0.0;
  61686. this._cam_axisZ.y = 0.0;
  61687. this._cam_axisZ.z = 1.0;
  61688. // cases when the World Matrix is to be computed first
  61689. if (this.billboard || this._depthSort) {
  61690. this.mesh.computeWorldMatrix(true);
  61691. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61692. }
  61693. // if the particles will always face the camera
  61694. if (this.billboard) {
  61695. // compute the camera position and un-rotate it by the current mesh rotation
  61696. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61697. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61698. this._cam_axisZ.normalize();
  61699. // same for camera up vector extracted from the cam view matrix
  61700. var view = this._camera.getViewMatrix(true);
  61701. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61702. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61703. this._cam_axisY.normalize();
  61704. this._cam_axisX.normalize();
  61705. }
  61706. // if depthSort, compute the camera global position in the mesh local system
  61707. if (this._depthSort) {
  61708. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61709. }
  61710. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61711. var idx = 0; // current position index in the global array positions32
  61712. var index = 0; // position start index in the global array positions32 of the current particle
  61713. var colidx = 0; // current color index in the global array colors32
  61714. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61715. var uvidx = 0; // current uv index in the global array uvs32
  61716. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61717. var pt = 0; // current index in the particle model shape
  61718. if (this.mesh.isFacetDataEnabled) {
  61719. this._computeBoundingBox = true;
  61720. }
  61721. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61722. if (this._computeBoundingBox) {
  61723. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61724. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61725. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61726. }
  61727. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61728. if (this.mesh._boundingInfo) {
  61729. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61730. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61731. }
  61732. }
  61733. }
  61734. // particle loop
  61735. index = this.particles[start]._pos;
  61736. var vpos = (index / 3) | 0;
  61737. colorIndex = vpos * 4;
  61738. uvIndex = vpos * 2;
  61739. for (var p = start; p <= end; p++) {
  61740. this._particle = this.particles[p];
  61741. this._shape = this._particle._model._shape;
  61742. this._shapeUV = this._particle._model._shapeUV;
  61743. // call to custom user function to update the particle properties
  61744. this.updateParticle(this._particle);
  61745. // camera-particle distance for depth sorting
  61746. if (this._depthSort && this._depthSortParticles) {
  61747. var dsp = this.depthSortedParticles[p];
  61748. dsp.ind = this._particle._ind;
  61749. dsp.indicesLength = this._particle._model._indicesLength;
  61750. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61751. }
  61752. // skip the computations for inactive or already invisible particles
  61753. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61754. // increment indexes for the next particle
  61755. pt = this._shape.length;
  61756. index += pt * 3;
  61757. colorIndex += pt * 4;
  61758. uvIndex += pt * 2;
  61759. continue;
  61760. }
  61761. if (this._particle.isVisible) {
  61762. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61763. this._particleHasParent = (this._particle.parentId !== null);
  61764. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61765. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61766. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61767. // particle rotation matrix
  61768. if (this.billboard) {
  61769. this._particle.rotation.x = 0.0;
  61770. this._particle.rotation.y = 0.0;
  61771. }
  61772. if (this._computeParticleRotation || this.billboard) {
  61773. if (this._particle.rotationQuaternion) {
  61774. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61775. }
  61776. else {
  61777. this._yaw = this._particle.rotation.y;
  61778. this._pitch = this._particle.rotation.x;
  61779. this._roll = this._particle.rotation.z;
  61780. this._quaternionRotationYPR();
  61781. }
  61782. this._quaternionToRotationMatrix();
  61783. }
  61784. if (this._particleHasParent) {
  61785. this._parent = this.particles[this._particle.parentId];
  61786. 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];
  61787. 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];
  61788. 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];
  61789. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61790. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61791. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61792. if (this._computeParticleRotation || this.billboard) {
  61793. 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];
  61794. 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];
  61795. 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];
  61796. 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];
  61797. 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];
  61798. 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];
  61799. 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];
  61800. 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];
  61801. 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];
  61802. }
  61803. }
  61804. else {
  61805. this._particle._globalPosition.x = this._particle.position.x;
  61806. this._particle._globalPosition.y = this._particle.position.y;
  61807. this._particle._globalPosition.z = this._particle.position.z;
  61808. if (this._computeParticleRotation || this.billboard) {
  61809. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61810. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61811. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61812. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61813. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61814. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61815. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61816. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61817. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61818. }
  61819. }
  61820. if (this._particle.translateFromPivot) {
  61821. this._pivotBackTranslation.x = 0.0;
  61822. this._pivotBackTranslation.y = 0.0;
  61823. this._pivotBackTranslation.z = 0.0;
  61824. }
  61825. else {
  61826. this._pivotBackTranslation.x = this._scaledPivot.x;
  61827. this._pivotBackTranslation.y = this._scaledPivot.y;
  61828. this._pivotBackTranslation.z = this._scaledPivot.z;
  61829. }
  61830. // particle vertex loop
  61831. for (pt = 0; pt < this._shape.length; pt++) {
  61832. idx = index + pt * 3;
  61833. colidx = colorIndex + pt * 4;
  61834. uvidx = uvIndex + pt * 2;
  61835. this._vertex.x = this._shape[pt].x;
  61836. this._vertex.y = this._shape[pt].y;
  61837. this._vertex.z = this._shape[pt].z;
  61838. if (this._computeParticleVertex) {
  61839. this.updateParticleVertex(this._particle, this._vertex, pt);
  61840. }
  61841. // positions
  61842. this._vertex.x *= this._particle.scaling.x;
  61843. this._vertex.y *= this._particle.scaling.y;
  61844. this._vertex.z *= this._particle.scaling.z;
  61845. this._vertex.x -= this._scaledPivot.x;
  61846. this._vertex.y -= this._scaledPivot.y;
  61847. this._vertex.z -= this._scaledPivot.z;
  61848. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61849. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61850. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61851. this._rotated.x += this._pivotBackTranslation.x;
  61852. this._rotated.y += this._pivotBackTranslation.y;
  61853. this._rotated.z += this._pivotBackTranslation.z;
  61854. 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;
  61855. 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;
  61856. 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;
  61857. if (this._computeBoundingBox) {
  61858. if (this._positions32[idx] < this._minimum.x) {
  61859. this._minimum.x = this._positions32[idx];
  61860. }
  61861. if (this._positions32[idx] > this._maximum.x) {
  61862. this._maximum.x = this._positions32[idx];
  61863. }
  61864. if (this._positions32[idx + 1] < this._minimum.y) {
  61865. this._minimum.y = this._positions32[idx + 1];
  61866. }
  61867. if (this._positions32[idx + 1] > this._maximum.y) {
  61868. this._maximum.y = this._positions32[idx + 1];
  61869. }
  61870. if (this._positions32[idx + 2] < this._minimum.z) {
  61871. this._minimum.z = this._positions32[idx + 2];
  61872. }
  61873. if (this._positions32[idx + 2] > this._maximum.z) {
  61874. this._maximum.z = this._positions32[idx + 2];
  61875. }
  61876. }
  61877. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  61878. if (!this._computeParticleVertex) {
  61879. this._normal.x = this._fixedNormal32[idx];
  61880. this._normal.y = this._fixedNormal32[idx + 1];
  61881. this._normal.z = this._fixedNormal32[idx + 2];
  61882. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  61883. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  61884. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  61885. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61886. 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;
  61887. 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;
  61888. }
  61889. if (this._computeParticleColor && this._particle.color) {
  61890. this._colors32[colidx] = this._particle.color.r;
  61891. this._colors32[colidx + 1] = this._particle.color.g;
  61892. this._colors32[colidx + 2] = this._particle.color.b;
  61893. this._colors32[colidx + 3] = this._particle.color.a;
  61894. }
  61895. if (this._computeParticleTexture) {
  61896. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61897. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61898. }
  61899. }
  61900. }
  61901. // particle just set invisible : scaled to zero and positioned at the origin
  61902. else {
  61903. this._particle._stillInvisible = true; // mark the particle as invisible
  61904. for (pt = 0; pt < this._shape.length; pt++) {
  61905. idx = index + pt * 3;
  61906. colidx = colorIndex + pt * 4;
  61907. uvidx = uvIndex + pt * 2;
  61908. this._positions32[idx] = 0.0;
  61909. this._positions32[idx + 1] = 0.0;
  61910. this._positions32[idx + 2] = 0.0;
  61911. this._normals32[idx] = 0.0;
  61912. this._normals32[idx + 1] = 0.0;
  61913. this._normals32[idx + 2] = 0.0;
  61914. if (this._computeParticleColor && this._particle.color) {
  61915. this._colors32[colidx] = this._particle.color.r;
  61916. this._colors32[colidx + 1] = this._particle.color.g;
  61917. this._colors32[colidx + 2] = this._particle.color.b;
  61918. this._colors32[colidx + 3] = this._particle.color.a;
  61919. }
  61920. if (this._computeParticleTexture) {
  61921. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61922. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61923. }
  61924. }
  61925. }
  61926. // if the particle intersections must be computed : update the bbInfo
  61927. if (this._particlesIntersect) {
  61928. var bInfo = this._particle._boundingInfo;
  61929. var bBox = bInfo.boundingBox;
  61930. var bSphere = bInfo.boundingSphere;
  61931. if (!this._bSphereOnly) {
  61932. // place, scale and rotate the particle bbox within the SPS local system, then update it
  61933. for (var b = 0; b < bBox.vectors.length; b++) {
  61934. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  61935. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  61936. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  61937. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61938. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61939. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61940. 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;
  61941. 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;
  61942. 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;
  61943. }
  61944. bBox._update(this.mesh._worldMatrix);
  61945. }
  61946. // place and scale the particle bouding sphere in the SPS local system, then update it
  61947. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  61948. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  61949. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  61950. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  61951. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  61952. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  61953. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  61954. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  61955. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  61956. 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));
  61957. bSphere._update(this.mesh._worldMatrix);
  61958. }
  61959. // increment indexes for the next particle
  61960. index = idx + 3;
  61961. colorIndex = colidx + 4;
  61962. uvIndex = uvidx + 2;
  61963. }
  61964. // if the VBO must be updated
  61965. if (update) {
  61966. if (this._computeParticleColor) {
  61967. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  61968. }
  61969. if (this._computeParticleTexture) {
  61970. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  61971. }
  61972. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61973. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  61974. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  61975. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  61976. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  61977. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  61978. for (var i = 0; i < this._normals32.length; i++) {
  61979. this._fixedNormal32[i] = this._normals32[i];
  61980. }
  61981. }
  61982. if (!this.mesh.areNormalsFrozen) {
  61983. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  61984. }
  61985. }
  61986. if (this._depthSort && this._depthSortParticles) {
  61987. this.depthSortedParticles.sort(this._depthSortFunction);
  61988. var dspl = this.depthSortedParticles.length;
  61989. var sorted = 0;
  61990. var lind = 0;
  61991. var sind = 0;
  61992. var sid = 0;
  61993. for (sorted = 0; sorted < dspl; sorted++) {
  61994. lind = this.depthSortedParticles[sorted].indicesLength;
  61995. sind = this.depthSortedParticles[sorted].ind;
  61996. for (var i = 0; i < lind; i++) {
  61997. this._indices32[sid] = this._indices[sind + i];
  61998. sid++;
  61999. }
  62000. }
  62001. this.mesh.updateIndices(this._indices32);
  62002. }
  62003. }
  62004. if (this._computeBoundingBox) {
  62005. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62006. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62007. }
  62008. this.afterUpdateParticles(start, end, update);
  62009. return this;
  62010. };
  62011. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62012. this._halfroll = this._roll * 0.5;
  62013. this._halfpitch = this._pitch * 0.5;
  62014. this._halfyaw = this._yaw * 0.5;
  62015. this._sinRoll = Math.sin(this._halfroll);
  62016. this._cosRoll = Math.cos(this._halfroll);
  62017. this._sinPitch = Math.sin(this._halfpitch);
  62018. this._cosPitch = Math.cos(this._halfpitch);
  62019. this._sinYaw = Math.sin(this._halfyaw);
  62020. this._cosYaw = Math.cos(this._halfyaw);
  62021. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62022. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62023. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62024. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62025. };
  62026. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62027. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62028. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62029. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62030. this._rotMatrix.m[3] = 0;
  62031. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62032. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62033. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62034. this._rotMatrix.m[7] = 0;
  62035. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62036. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62037. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62038. this._rotMatrix.m[11] = 0;
  62039. this._rotMatrix.m[12] = 0;
  62040. this._rotMatrix.m[13] = 0;
  62041. this._rotMatrix.m[14] = 0;
  62042. this._rotMatrix.m[15] = 1.0;
  62043. };
  62044. /**
  62045. * Disposes the SPS.
  62046. */
  62047. SolidParticleSystem.prototype.dispose = function () {
  62048. this.mesh.dispose();
  62049. this.vars = null;
  62050. // drop references to internal big arrays for the GC
  62051. this._positions = null;
  62052. this._indices = null;
  62053. this._normals = null;
  62054. this._uvs = null;
  62055. this._colors = null;
  62056. this._indices32 = null;
  62057. this._positions32 = null;
  62058. this._normals32 = null;
  62059. this._fixedNormal32 = null;
  62060. this._uvs32 = null;
  62061. this._colors32 = null;
  62062. this.pickedParticles = null;
  62063. };
  62064. /**
  62065. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62066. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62067. * @returns the SPS.
  62068. */
  62069. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62070. if (!this._isVisibilityBoxLocked) {
  62071. this.mesh.refreshBoundingInfo();
  62072. }
  62073. return this;
  62074. };
  62075. /**
  62076. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  62077. * @param size the size (float) of the visibility box
  62078. * note : this doesn't lock the SPS mesh bounding box.
  62079. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62080. */
  62081. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  62082. var vis = size / 2;
  62083. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  62084. };
  62085. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  62086. /**
  62087. * Gets whether the SPS as always visible or not
  62088. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62089. */
  62090. get: function () {
  62091. return this._alwaysVisible;
  62092. },
  62093. /**
  62094. * Sets the SPS as always visible or not
  62095. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62096. */
  62097. set: function (val) {
  62098. this._alwaysVisible = val;
  62099. this.mesh.alwaysSelectAsActiveMesh = val;
  62100. },
  62101. enumerable: true,
  62102. configurable: true
  62103. });
  62104. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  62105. /**
  62106. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62107. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62108. */
  62109. get: function () {
  62110. return this._isVisibilityBoxLocked;
  62111. },
  62112. /**
  62113. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62114. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62115. */
  62116. set: function (val) {
  62117. this._isVisibilityBoxLocked = val;
  62118. var boundingInfo = this.mesh.getBoundingInfo();
  62119. boundingInfo.isLocked = val;
  62120. },
  62121. enumerable: true,
  62122. configurable: true
  62123. });
  62124. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  62125. /**
  62126. * Gets if `setParticles()` computes the particle rotations or not.
  62127. * Default value : true. The SPS is faster when it's set to false.
  62128. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62129. */
  62130. get: function () {
  62131. return this._computeParticleRotation;
  62132. },
  62133. /**
  62134. * Tells to `setParticles()` to compute the particle rotations or not.
  62135. * Default value : true. The SPS is faster when it's set to false.
  62136. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62137. */
  62138. set: function (val) {
  62139. this._computeParticleRotation = val;
  62140. },
  62141. enumerable: true,
  62142. configurable: true
  62143. });
  62144. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  62145. /**
  62146. * Gets if `setParticles()` computes the particle colors or not.
  62147. * Default value : true. The SPS is faster when it's set to false.
  62148. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62149. */
  62150. get: function () {
  62151. return this._computeParticleColor;
  62152. },
  62153. /**
  62154. * Tells to `setParticles()` to compute the particle colors or not.
  62155. * Default value : true. The SPS is faster when it's set to false.
  62156. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62157. */
  62158. set: function (val) {
  62159. this._computeParticleColor = val;
  62160. },
  62161. enumerable: true,
  62162. configurable: true
  62163. });
  62164. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  62165. /**
  62166. * Gets if `setParticles()` computes the particle textures or not.
  62167. * Default value : true. The SPS is faster when it's set to false.
  62168. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  62169. */
  62170. get: function () {
  62171. return this._computeParticleTexture;
  62172. },
  62173. set: function (val) {
  62174. this._computeParticleTexture = val;
  62175. },
  62176. enumerable: true,
  62177. configurable: true
  62178. });
  62179. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  62180. /**
  62181. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  62182. * Default value : false. The SPS is faster when it's set to false.
  62183. * Note : the particle custom vertex positions aren't stored values.
  62184. */
  62185. get: function () {
  62186. return this._computeParticleVertex;
  62187. },
  62188. /**
  62189. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  62190. * Default value : false. The SPS is faster when it's set to false.
  62191. * Note : the particle custom vertex positions aren't stored values.
  62192. */
  62193. set: function (val) {
  62194. this._computeParticleVertex = val;
  62195. },
  62196. enumerable: true,
  62197. configurable: true
  62198. });
  62199. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  62200. /**
  62201. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  62202. */
  62203. get: function () {
  62204. return this._computeBoundingBox;
  62205. },
  62206. /**
  62207. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  62208. */
  62209. set: function (val) {
  62210. this._computeBoundingBox = val;
  62211. },
  62212. enumerable: true,
  62213. configurable: true
  62214. });
  62215. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  62216. /**
  62217. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  62218. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62219. * Default : `true`
  62220. */
  62221. get: function () {
  62222. return this._depthSortParticles;
  62223. },
  62224. /**
  62225. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  62226. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62227. * Default : `true`
  62228. */
  62229. set: function (val) {
  62230. this._depthSortParticles = val;
  62231. },
  62232. enumerable: true,
  62233. configurable: true
  62234. });
  62235. // =======================================================================
  62236. // Particle behavior logic
  62237. // these following methods may be overwritten by the user to fit his needs
  62238. /**
  62239. * This function does nothing. It may be overwritten to set all the particle first values.
  62240. * The SPS doesn't call this function, you may have to call it by your own.
  62241. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62242. */
  62243. SolidParticleSystem.prototype.initParticles = function () {
  62244. };
  62245. /**
  62246. * This function does nothing. It may be overwritten to recycle a particle.
  62247. * The SPS doesn't call this function, you may have to call it by your own.
  62248. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62249. * @param particle The particle to recycle
  62250. * @returns the recycled particle
  62251. */
  62252. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  62253. return particle;
  62254. };
  62255. /**
  62256. * Updates a particle : this function should be overwritten by the user.
  62257. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  62258. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62259. * @example : just set a particle position or velocity and recycle conditions
  62260. * @param particle The particle to update
  62261. * @returns the updated particle
  62262. */
  62263. SolidParticleSystem.prototype.updateParticle = function (particle) {
  62264. return particle;
  62265. };
  62266. /**
  62267. * Updates a vertex of a particle : it can be overwritten by the user.
  62268. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  62269. * @param particle the current particle
  62270. * @param vertex the current index of the current particle
  62271. * @param pt the index of the current vertex in the particle shape
  62272. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  62273. * @example : just set a vertex particle position
  62274. * @returns the updated vertex
  62275. */
  62276. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  62277. return vertex;
  62278. };
  62279. /**
  62280. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  62281. * This does nothing and may be overwritten by the user.
  62282. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62283. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62284. * @param update the boolean update value actually passed to setParticles()
  62285. */
  62286. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  62287. };
  62288. /**
  62289. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  62290. * This will be passed three parameters.
  62291. * This does nothing and may be overwritten by the user.
  62292. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62293. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62294. * @param update the boolean update value actually passed to setParticles()
  62295. */
  62296. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62297. };
  62298. return SolidParticleSystem;
  62299. }());
  62300. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62301. })(BABYLON || (BABYLON = {}));
  62302. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62303. var BABYLON;
  62304. (function (BABYLON) {
  62305. /**
  62306. * Class containing static functions to help procedurally build meshes
  62307. */
  62308. var MeshBuilder = /** @class */ (function () {
  62309. function MeshBuilder() {
  62310. }
  62311. MeshBuilder.updateSideOrientation = function (orientation) {
  62312. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62313. return BABYLON.Mesh.DOUBLESIDE;
  62314. }
  62315. if (orientation === undefined || orientation === null) {
  62316. return BABYLON.Mesh.FRONTSIDE;
  62317. }
  62318. return orientation;
  62319. };
  62320. /**
  62321. * Creates a box mesh
  62322. * * The parameter `size` sets the size (float) of each box side (default 1)
  62323. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62324. * * 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)
  62325. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62326. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62327. * * 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
  62328. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62329. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62330. * @param name defines the name of the mesh
  62331. * @param options defines the options used to create the mesh
  62332. * @param scene defines the hosting scene
  62333. * @returns the box mesh
  62334. */
  62335. MeshBuilder.CreateBox = function (name, options, scene) {
  62336. if (scene === void 0) { scene = null; }
  62337. var box = new BABYLON.Mesh(name, scene);
  62338. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62339. box._originalBuilderSideOrientation = options.sideOrientation;
  62340. var vertexData = BABYLON.VertexData.CreateBox(options);
  62341. vertexData.applyToMesh(box, options.updatable);
  62342. return box;
  62343. };
  62344. /**
  62345. * Creates a sphere mesh
  62346. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62347. * * 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`)
  62348. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62349. * * 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
  62350. * * 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)
  62351. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62352. * * 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
  62353. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62354. * @param name defines the name of the mesh
  62355. * @param options defines the options used to create the mesh
  62356. * @param scene defines the hosting scene
  62357. * @returns the sphere mesh
  62358. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62359. */
  62360. MeshBuilder.CreateSphere = function (name, options, scene) {
  62361. var sphere = new BABYLON.Mesh(name, scene);
  62362. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62363. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62364. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62365. vertexData.applyToMesh(sphere, options.updatable);
  62366. return sphere;
  62367. };
  62368. /**
  62369. * Creates a plane polygonal mesh. By default, this is a disc
  62370. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62371. * * 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
  62372. * * 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
  62373. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62374. * * 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
  62375. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62376. * @param name defines the name of the mesh
  62377. * @param options defines the options used to create the mesh
  62378. * @param scene defines the hosting scene
  62379. * @returns the plane polygonal mesh
  62380. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62381. */
  62382. MeshBuilder.CreateDisc = function (name, options, scene) {
  62383. if (scene === void 0) { scene = null; }
  62384. var disc = new BABYLON.Mesh(name, scene);
  62385. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62386. disc._originalBuilderSideOrientation = options.sideOrientation;
  62387. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62388. vertexData.applyToMesh(disc, options.updatable);
  62389. return disc;
  62390. };
  62391. /**
  62392. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62393. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62394. * * 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`)
  62395. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62396. * * 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
  62397. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62398. * * 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
  62399. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62400. * @param name defines the name of the mesh
  62401. * @param options defines the options used to create the mesh
  62402. * @param scene defines the hosting scene
  62403. * @returns the icosahedron mesh
  62404. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62405. */
  62406. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62407. var sphere = new BABYLON.Mesh(name, scene);
  62408. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62409. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62410. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62411. vertexData.applyToMesh(sphere, options.updatable);
  62412. return sphere;
  62413. };
  62414. ;
  62415. /**
  62416. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62417. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62418. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62419. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62420. * * 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
  62421. * * 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
  62422. * * 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
  62423. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62424. * * 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
  62425. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62426. * * 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
  62427. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62428. * * 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
  62429. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62430. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62431. * @param name defines the name of the mesh
  62432. * @param options defines the options used to create the mesh
  62433. * @param scene defines the hosting scene
  62434. * @returns the ribbon mesh
  62435. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62436. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62437. */
  62438. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62439. if (scene === void 0) { scene = null; }
  62440. var pathArray = options.pathArray;
  62441. var closeArray = options.closeArray;
  62442. var closePath = options.closePath;
  62443. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62444. var instance = options.instance;
  62445. var updatable = options.updatable;
  62446. if (instance) { // existing ribbon instance update
  62447. // positionFunction : ribbon case
  62448. // only pathArray and sideOrientation parameters are taken into account for positions update
  62449. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62450. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62451. var positionFunction = function (positions) {
  62452. var minlg = pathArray[0].length;
  62453. var i = 0;
  62454. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62455. for (var si = 1; si <= ns; si++) {
  62456. for (var p = 0; p < pathArray.length; p++) {
  62457. var path = pathArray[p];
  62458. var l = path.length;
  62459. minlg = (minlg < l) ? minlg : l;
  62460. var j = 0;
  62461. while (j < minlg) {
  62462. positions[i] = path[j].x;
  62463. positions[i + 1] = path[j].y;
  62464. positions[i + 2] = path[j].z;
  62465. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62466. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62467. }
  62468. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62469. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62470. }
  62471. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62472. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62473. }
  62474. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62475. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62476. }
  62477. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62478. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62479. }
  62480. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62481. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62482. }
  62483. j++;
  62484. i += 3;
  62485. }
  62486. if (instance._closePath) {
  62487. positions[i] = path[0].x;
  62488. positions[i + 1] = path[0].y;
  62489. positions[i + 2] = path[0].z;
  62490. i += 3;
  62491. }
  62492. }
  62493. }
  62494. };
  62495. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62496. positionFunction(positions);
  62497. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62498. instance._boundingInfo.update(instance._worldMatrix);
  62499. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62500. if (options.colors) {
  62501. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62502. for (var c = 0; c < options.colors.length; c++) {
  62503. colors[c * 4] = options.colors[c].r;
  62504. colors[c * 4 + 1] = options.colors[c].g;
  62505. colors[c * 4 + 2] = options.colors[c].b;
  62506. colors[c * 4 + 3] = options.colors[c].a;
  62507. }
  62508. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62509. }
  62510. if (options.uvs) {
  62511. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62512. for (var i = 0; i < options.uvs.length; i++) {
  62513. uvs[i * 2] = options.uvs[i].x;
  62514. uvs[i * 2 + 1] = options.uvs[i].y;
  62515. }
  62516. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62517. }
  62518. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62519. var indices = instance.getIndices();
  62520. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62521. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62522. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62523. if (instance._closePath) {
  62524. var indexFirst = 0;
  62525. var indexLast = 0;
  62526. for (var p = 0; p < pathArray.length; p++) {
  62527. indexFirst = instance._idx[p] * 3;
  62528. if (p + 1 < pathArray.length) {
  62529. indexLast = (instance._idx[p + 1] - 1) * 3;
  62530. }
  62531. else {
  62532. indexLast = normals.length - 3;
  62533. }
  62534. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62535. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62536. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62537. normals[indexLast] = normals[indexFirst];
  62538. normals[indexLast + 1] = normals[indexFirst + 1];
  62539. normals[indexLast + 2] = normals[indexFirst + 2];
  62540. }
  62541. }
  62542. if (!(instance.areNormalsFrozen)) {
  62543. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62544. }
  62545. }
  62546. return instance;
  62547. }
  62548. else { // new ribbon creation
  62549. var ribbon = new BABYLON.Mesh(name, scene);
  62550. ribbon._originalBuilderSideOrientation = sideOrientation;
  62551. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62552. if (closePath) {
  62553. ribbon._idx = vertexData._idx;
  62554. }
  62555. ribbon._closePath = closePath;
  62556. ribbon._closeArray = closeArray;
  62557. vertexData.applyToMesh(ribbon, updatable);
  62558. return ribbon;
  62559. }
  62560. };
  62561. /**
  62562. * Creates a cylinder or a cone mesh
  62563. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62564. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62565. * * 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.
  62566. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62567. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62568. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62569. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62570. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62571. * * 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).
  62572. * * 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
  62573. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62574. * * 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
  62575. * * 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.
  62576. * * If `enclose` is false, a ring surface is one element.
  62577. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62578. * * 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
  62579. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62580. * * 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
  62581. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62582. * @param name defines the name of the mesh
  62583. * @param options defines the options used to create the mesh
  62584. * @param scene defines the hosting scene
  62585. * @returns the cylinder mesh
  62586. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62587. */
  62588. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62589. var cylinder = new BABYLON.Mesh(name, scene);
  62590. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62591. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62592. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62593. vertexData.applyToMesh(cylinder, options.updatable);
  62594. return cylinder;
  62595. };
  62596. /**
  62597. * Creates a torus mesh
  62598. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62599. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62600. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62601. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62602. * * 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
  62603. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62604. * @param name defines the name of the mesh
  62605. * @param options defines the options used to create the mesh
  62606. * @param scene defines the hosting scene
  62607. * @returns the torus mesh
  62608. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62609. */
  62610. MeshBuilder.CreateTorus = function (name, options, scene) {
  62611. var torus = new BABYLON.Mesh(name, scene);
  62612. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62613. torus._originalBuilderSideOrientation = options.sideOrientation;
  62614. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62615. vertexData.applyToMesh(torus, options.updatable);
  62616. return torus;
  62617. };
  62618. /**
  62619. * Creates a torus knot mesh
  62620. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62621. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62622. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62623. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62624. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62625. * * 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
  62626. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62627. * @param name defines the name of the mesh
  62628. * @param options defines the options used to create the mesh
  62629. * @param scene defines the hosting scene
  62630. * @returns the torus knot mesh
  62631. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62632. */
  62633. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62634. var torusKnot = new BABYLON.Mesh(name, scene);
  62635. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62636. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62637. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62638. vertexData.applyToMesh(torusKnot, options.updatable);
  62639. return torusKnot;
  62640. };
  62641. /**
  62642. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62643. * * 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
  62644. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62645. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62646. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62647. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62648. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62649. * * 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
  62650. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62651. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62652. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62653. * @param name defines the name of the new line system
  62654. * @param options defines the options used to create the line system
  62655. * @param scene defines the hosting scene
  62656. * @returns a new line system mesh
  62657. */
  62658. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62659. var instance = options.instance;
  62660. var lines = options.lines;
  62661. var colors = options.colors;
  62662. if (instance) { // lines update
  62663. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62664. var vertexColor;
  62665. var lineColors;
  62666. if (colors) {
  62667. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62668. }
  62669. var i = 0;
  62670. var c = 0;
  62671. for (var l = 0; l < lines.length; l++) {
  62672. var points = lines[l];
  62673. for (var p = 0; p < points.length; p++) {
  62674. positions[i] = points[p].x;
  62675. positions[i + 1] = points[p].y;
  62676. positions[i + 2] = points[p].z;
  62677. if (colors && vertexColor) {
  62678. lineColors = colors[l];
  62679. vertexColor[c] = lineColors[p].r;
  62680. vertexColor[c + 1] = lineColors[p].g;
  62681. vertexColor[c + 2] = lineColors[p].b;
  62682. vertexColor[c + 3] = lineColors[p].a;
  62683. c += 4;
  62684. }
  62685. i += 3;
  62686. }
  62687. }
  62688. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62689. if (colors && vertexColor) {
  62690. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62691. }
  62692. return instance;
  62693. }
  62694. // line system creation
  62695. var useVertexColor = (colors) ? true : false;
  62696. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62697. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62698. vertexData.applyToMesh(lineSystem, options.updatable);
  62699. return lineSystem;
  62700. };
  62701. /**
  62702. * Creates a line mesh
  62703. * 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
  62704. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62705. * * The parameter `points` is an array successive Vector3
  62706. * * 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
  62707. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62708. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62709. * * When updating an instance, remember that only point positions can change, not the number of points
  62710. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62711. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62712. * @param name defines the name of the new line system
  62713. * @param options defines the options used to create the line system
  62714. * @param scene defines the hosting scene
  62715. * @returns a new line mesh
  62716. */
  62717. MeshBuilder.CreateLines = function (name, options, scene) {
  62718. if (scene === void 0) { scene = null; }
  62719. var colors = (options.colors) ? [options.colors] : null;
  62720. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62721. return lines;
  62722. };
  62723. /**
  62724. * Creates a dashed line mesh
  62725. * * 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
  62726. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62727. * * The parameter `points` is an array successive Vector3
  62728. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62729. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62730. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62731. * * 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
  62732. * * When updating an instance, remember that only point positions can change, not the number of points
  62733. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62734. * @param name defines the name of the mesh
  62735. * @param options defines the options used to create the mesh
  62736. * @param scene defines the hosting scene
  62737. * @returns the dashed line mesh
  62738. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62739. */
  62740. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62741. if (scene === void 0) { scene = null; }
  62742. var points = options.points;
  62743. var instance = options.instance;
  62744. var gapSize = options.gapSize || 1;
  62745. var dashSize = options.dashSize || 3;
  62746. if (instance) { // dashed lines update
  62747. var positionFunction = function (positions) {
  62748. var curvect = BABYLON.Vector3.Zero();
  62749. var nbSeg = positions.length / 6;
  62750. var lg = 0;
  62751. var nb = 0;
  62752. var shft = 0;
  62753. var dashshft = 0;
  62754. var curshft = 0;
  62755. var p = 0;
  62756. var i = 0;
  62757. var j = 0;
  62758. for (i = 0; i < points.length - 1; i++) {
  62759. points[i + 1].subtractToRef(points[i], curvect);
  62760. lg += curvect.length();
  62761. }
  62762. shft = lg / nbSeg;
  62763. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62764. for (i = 0; i < points.length - 1; i++) {
  62765. points[i + 1].subtractToRef(points[i], curvect);
  62766. nb = Math.floor(curvect.length() / shft);
  62767. curvect.normalize();
  62768. j = 0;
  62769. while (j < nb && p < positions.length) {
  62770. curshft = shft * j;
  62771. positions[p] = points[i].x + curshft * curvect.x;
  62772. positions[p + 1] = points[i].y + curshft * curvect.y;
  62773. positions[p + 2] = points[i].z + curshft * curvect.z;
  62774. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62775. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62776. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62777. p += 6;
  62778. j++;
  62779. }
  62780. }
  62781. while (p < positions.length) {
  62782. positions[p] = points[i].x;
  62783. positions[p + 1] = points[i].y;
  62784. positions[p + 2] = points[i].z;
  62785. p += 3;
  62786. }
  62787. };
  62788. instance.updateMeshPositions(positionFunction, false);
  62789. return instance;
  62790. }
  62791. // dashed lines creation
  62792. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62793. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62794. vertexData.applyToMesh(dashedLines, options.updatable);
  62795. dashedLines.dashSize = dashSize;
  62796. dashedLines.gapSize = gapSize;
  62797. return dashedLines;
  62798. };
  62799. /**
  62800. * 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.
  62801. * * 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.
  62802. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62803. * * 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.
  62804. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62805. * * 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
  62806. * * 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
  62807. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62808. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62809. * * 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
  62810. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62811. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62812. * @param name defines the name of the mesh
  62813. * @param options defines the options used to create the mesh
  62814. * @param scene defines the hosting scene
  62815. * @returns the extruded shape mesh
  62816. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62817. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62818. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62819. */
  62820. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62821. if (scene === void 0) { scene = null; }
  62822. var path = options.path;
  62823. var shape = options.shape;
  62824. var scale = options.scale || 1;
  62825. var rotation = options.rotation || 0;
  62826. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62827. var updatable = options.updatable;
  62828. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62829. var instance = options.instance || null;
  62830. var invertUV = options.invertUV || false;
  62831. 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);
  62832. };
  62833. /**
  62834. * Creates an custom extruded shape mesh.
  62835. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62836. * * 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.
  62837. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62838. * * 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
  62839. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62840. * * 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
  62841. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62842. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62843. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62844. * * 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
  62845. * * 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
  62846. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62847. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62848. * * 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
  62849. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62850. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62851. * @param name defines the name of the mesh
  62852. * @param options defines the options used to create the mesh
  62853. * @param scene defines the hosting scene
  62854. * @returns the custom extruded shape mesh
  62855. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62856. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62857. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62858. */
  62859. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62860. var path = options.path;
  62861. var shape = options.shape;
  62862. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62863. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62864. var ribbonCloseArray = options.ribbonCloseArray || false;
  62865. var ribbonClosePath = options.ribbonClosePath || false;
  62866. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62867. var updatable = options.updatable;
  62868. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62869. var instance = options.instance;
  62870. var invertUV = options.invertUV || false;
  62871. 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);
  62872. };
  62873. /**
  62874. * Creates lathe mesh.
  62875. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  62876. * * 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
  62877. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  62878. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  62879. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  62880. * * 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
  62881. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  62882. * * 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
  62883. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62884. * * 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
  62885. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62886. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62887. * @param name defines the name of the mesh
  62888. * @param options defines the options used to create the mesh
  62889. * @param scene defines the hosting scene
  62890. * @returns the lathe mesh
  62891. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  62892. */
  62893. MeshBuilder.CreateLathe = function (name, options, scene) {
  62894. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  62895. var closed = (options.closed === undefined) ? true : options.closed;
  62896. var shape = options.shape;
  62897. var radius = options.radius || 1;
  62898. var tessellation = options.tessellation || 64;
  62899. var clip = options.clip || 0;
  62900. var updatable = options.updatable;
  62901. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62902. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62903. var pi2 = Math.PI * 2;
  62904. var paths = new Array();
  62905. var invertUV = options.invertUV || false;
  62906. var i = 0;
  62907. var p = 0;
  62908. var step = pi2 / tessellation * arc;
  62909. var rotated;
  62910. var path = new Array();
  62911. for (i = 0; i <= tessellation - clip; i++) {
  62912. var path = [];
  62913. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  62914. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  62915. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  62916. }
  62917. for (p = 0; p < shape.length; p++) {
  62918. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  62919. path.push(rotated);
  62920. }
  62921. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  62922. 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));
  62923. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  62924. }
  62925. paths.push(path);
  62926. }
  62927. // lathe ribbon
  62928. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62929. return lathe;
  62930. };
  62931. /**
  62932. * Creates a plane mesh
  62933. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  62934. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  62935. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  62936. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62937. * * 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
  62938. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62939. * @param name defines the name of the mesh
  62940. * @param options defines the options used to create the mesh
  62941. * @param scene defines the hosting scene
  62942. * @returns the plane mesh
  62943. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62944. */
  62945. MeshBuilder.CreatePlane = function (name, options, scene) {
  62946. var plane = new BABYLON.Mesh(name, scene);
  62947. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62948. plane._originalBuilderSideOrientation = options.sideOrientation;
  62949. var vertexData = BABYLON.VertexData.CreatePlane(options);
  62950. vertexData.applyToMesh(plane, options.updatable);
  62951. if (options.sourcePlane) {
  62952. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  62953. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  62954. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  62955. plane.rotate(vectorProduct, product);
  62956. }
  62957. return plane;
  62958. };
  62959. /**
  62960. * Creates a ground mesh
  62961. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  62962. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  62963. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62964. * @param name defines the name of the mesh
  62965. * @param options defines the options used to create the mesh
  62966. * @param scene defines the hosting scene
  62967. * @returns the ground mesh
  62968. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62969. */
  62970. MeshBuilder.CreateGround = function (name, options, scene) {
  62971. var ground = new BABYLON.GroundMesh(name, scene);
  62972. ground._setReady(false);
  62973. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  62974. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  62975. ground._width = options.width || 1;
  62976. ground._height = options.height || 1;
  62977. ground._maxX = ground._width / 2;
  62978. ground._maxZ = ground._height / 2;
  62979. ground._minX = -ground._maxX;
  62980. ground._minZ = -ground._maxZ;
  62981. var vertexData = BABYLON.VertexData.CreateGround(options);
  62982. vertexData.applyToMesh(ground, options.updatable);
  62983. ground._setReady(true);
  62984. return ground;
  62985. };
  62986. /**
  62987. * Creates a tiled ground mesh
  62988. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  62989. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  62990. * * 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
  62991. * * 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
  62992. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62993. * @param name defines the name of the mesh
  62994. * @param options defines the options used to create the mesh
  62995. * @param scene defines the hosting scene
  62996. * @returns the tiled ground mesh
  62997. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  62998. */
  62999. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63000. var tiledGround = new BABYLON.Mesh(name, scene);
  63001. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63002. vertexData.applyToMesh(tiledGround, options.updatable);
  63003. return tiledGround;
  63004. };
  63005. /**
  63006. * Creates a ground mesh from a height map
  63007. * * The parameter `url` sets the URL of the height map image resource.
  63008. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63009. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63010. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63011. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63012. * * 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.
  63013. * * 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).
  63014. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63015. * @param name defines the name of the mesh
  63016. * @param url defines the url to the height map
  63017. * @param options defines the options used to create the mesh
  63018. * @param scene defines the hosting scene
  63019. * @returns the ground mesh
  63020. * @see http://doc.babylonjs.com/babylon101/height_map
  63021. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63022. */
  63023. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63024. var width = options.width || 10.0;
  63025. var height = options.height || 10.0;
  63026. var subdivisions = options.subdivisions || 1 | 0;
  63027. var minHeight = options.minHeight || 0.0;
  63028. var maxHeight = options.maxHeight || 1.0;
  63029. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63030. var updatable = options.updatable;
  63031. var onReady = options.onReady;
  63032. var ground = new BABYLON.GroundMesh(name, scene);
  63033. ground._subdivisionsX = subdivisions;
  63034. ground._subdivisionsY = subdivisions;
  63035. ground._width = width;
  63036. ground._height = height;
  63037. ground._maxX = ground._width / 2.0;
  63038. ground._maxZ = ground._height / 2.0;
  63039. ground._minX = -ground._maxX;
  63040. ground._minZ = -ground._maxZ;
  63041. ground._setReady(false);
  63042. var onload = function (img) {
  63043. // Getting height map data
  63044. var canvas = document.createElement("canvas");
  63045. var context = canvas.getContext("2d");
  63046. if (!context) {
  63047. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63048. }
  63049. if (scene.isDisposed) {
  63050. return;
  63051. }
  63052. var bufferWidth = img.width;
  63053. var bufferHeight = img.height;
  63054. canvas.width = bufferWidth;
  63055. canvas.height = bufferHeight;
  63056. context.drawImage(img, 0, 0);
  63057. // Create VertexData from map data
  63058. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63059. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63060. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63061. width: width, height: height,
  63062. subdivisions: subdivisions,
  63063. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63064. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63065. });
  63066. vertexData.applyToMesh(ground, updatable);
  63067. //execute ready callback, if set
  63068. if (onReady) {
  63069. onReady(ground);
  63070. }
  63071. ground._setReady(true);
  63072. };
  63073. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63074. return ground;
  63075. };
  63076. /**
  63077. * Creates a polygon mesh
  63078. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  63079. * * 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
  63080. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63081. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63082. * * 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)
  63083. * * Remember you can only change the shape positions, not their number when updating a polygon
  63084. * @param name defines the name of the mesh
  63085. * @param options defines the options used to create the mesh
  63086. * @param scene defines the hosting scene
  63087. * @returns the polygon mesh
  63088. */
  63089. MeshBuilder.CreatePolygon = function (name, options, scene) {
  63090. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63091. var shape = options.shape;
  63092. var holes = options.holes || [];
  63093. var depth = options.depth || 0;
  63094. var contours = [];
  63095. var hole = [];
  63096. for (var i = 0; i < shape.length; i++) {
  63097. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  63098. }
  63099. var epsilon = 0.00000001;
  63100. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  63101. contours.pop();
  63102. }
  63103. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  63104. for (var hNb = 0; hNb < holes.length; hNb++) {
  63105. hole = [];
  63106. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  63107. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  63108. }
  63109. polygonTriangulation.addHole(hole);
  63110. }
  63111. var polygon = polygonTriangulation.build(options.updatable, depth);
  63112. polygon._originalBuilderSideOrientation = options.sideOrientation;
  63113. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  63114. vertexData.applyToMesh(polygon, options.updatable);
  63115. return polygon;
  63116. };
  63117. ;
  63118. /**
  63119. * Creates an extruded polygon mesh, with depth in the Y direction.
  63120. * * 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)
  63121. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63122. * @param name defines the name of the mesh
  63123. * @param options defines the options used to create the mesh
  63124. * @param scene defines the hosting scene
  63125. * @returns the polygon mesh
  63126. */
  63127. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  63128. return MeshBuilder.CreatePolygon(name, options, scene);
  63129. };
  63130. ;
  63131. /**
  63132. * Creates a tube mesh.
  63133. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63134. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  63135. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  63136. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  63137. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  63138. * * 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)
  63139. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  63140. * * 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
  63141. * * 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
  63142. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63143. * * 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
  63144. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63145. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63146. * @param name defines the name of the mesh
  63147. * @param options defines the options used to create the mesh
  63148. * @param scene defines the hosting scene
  63149. * @returns the tube mesh
  63150. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63151. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  63152. */
  63153. MeshBuilder.CreateTube = function (name, options, scene) {
  63154. var path = options.path;
  63155. var instance = options.instance;
  63156. var radius = 1.0;
  63157. if (instance) {
  63158. radius = instance.radius;
  63159. }
  63160. if (options.radius !== undefined) {
  63161. radius = options.radius;
  63162. }
  63163. ;
  63164. var tessellation = options.tessellation || 64 | 0;
  63165. var radiusFunction = options.radiusFunction || null;
  63166. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63167. var invertUV = options.invertUV || false;
  63168. var updatable = options.updatable;
  63169. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63170. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  63171. // tube geometry
  63172. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  63173. var tangents = path3D.getTangents();
  63174. var normals = path3D.getNormals();
  63175. var distances = path3D.getDistances();
  63176. var pi2 = Math.PI * 2;
  63177. var step = pi2 / tessellation * arc;
  63178. var returnRadius = function () { return radius; };
  63179. var radiusFunctionFinal = radiusFunction || returnRadius;
  63180. var circlePath;
  63181. var rad;
  63182. var normal;
  63183. var rotated;
  63184. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63185. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63186. for (var i = 0; i < path.length; i++) {
  63187. rad = radiusFunctionFinal(i, distances[i]); // current radius
  63188. circlePath = Array(); // current circle array
  63189. normal = normals[i]; // current normal
  63190. for (var t = 0; t < tessellation; t++) {
  63191. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  63192. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  63193. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  63194. rotated.scaleInPlace(rad).addInPlace(path[i]);
  63195. circlePath[t] = rotated;
  63196. }
  63197. circlePaths[index] = circlePath;
  63198. index++;
  63199. }
  63200. // cap
  63201. var capPath = function (nbPoints, pathIndex) {
  63202. var pointCap = Array();
  63203. for (var i = 0; i < nbPoints; i++) {
  63204. pointCap.push(path[pathIndex]);
  63205. }
  63206. return pointCap;
  63207. };
  63208. switch (cap) {
  63209. case BABYLON.Mesh.NO_CAP:
  63210. break;
  63211. case BABYLON.Mesh.CAP_START:
  63212. circlePaths[0] = capPath(tessellation, 0);
  63213. circlePaths[1] = circlePaths[2].slice(0);
  63214. break;
  63215. case BABYLON.Mesh.CAP_END:
  63216. circlePaths[index] = circlePaths[index - 1].slice(0);
  63217. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63218. break;
  63219. case BABYLON.Mesh.CAP_ALL:
  63220. circlePaths[0] = capPath(tessellation, 0);
  63221. circlePaths[1] = circlePaths[2].slice(0);
  63222. circlePaths[index] = circlePaths[index - 1].slice(0);
  63223. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63224. break;
  63225. default:
  63226. break;
  63227. }
  63228. return circlePaths;
  63229. };
  63230. var path3D;
  63231. var pathArray;
  63232. if (instance) { // tube update
  63233. var arc = options.arc || instance.arc;
  63234. path3D = (instance.path3D).update(path);
  63235. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  63236. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  63237. instance.path3D = path3D;
  63238. instance.pathArray = pathArray;
  63239. instance.arc = arc;
  63240. instance.radius = radius;
  63241. return instance;
  63242. }
  63243. // tube creation
  63244. path3D = new BABYLON.Path3D(path);
  63245. var newPathArray = new Array();
  63246. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63247. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  63248. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63249. tube.pathArray = pathArray;
  63250. tube.path3D = path3D;
  63251. tube.tessellation = tessellation;
  63252. tube.cap = cap;
  63253. tube.arc = options.arc;
  63254. tube.radius = radius;
  63255. return tube;
  63256. };
  63257. /**
  63258. * Creates a polyhedron mesh
  63259. * * 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
  63260. * * The parameter `size` (positive float, default 1) sets the polygon size
  63261. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  63262. * * 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`
  63263. * * 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
  63264. * * 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)`)
  63265. * * 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
  63266. * * 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
  63267. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63268. * * 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
  63269. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63270. * @param name defines the name of the mesh
  63271. * @param options defines the options used to create the mesh
  63272. * @param scene defines the hosting scene
  63273. * @returns the polyhedron mesh
  63274. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  63275. */
  63276. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  63277. var polyhedron = new BABYLON.Mesh(name, scene);
  63278. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63279. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  63280. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  63281. vertexData.applyToMesh(polyhedron, options.updatable);
  63282. return polyhedron;
  63283. };
  63284. /**
  63285. * Creates a decal mesh.
  63286. * 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
  63287. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  63288. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  63289. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  63290. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  63291. * @param name defines the name of the mesh
  63292. * @param sourceMesh defines the mesh where the decal must be applied
  63293. * @param options defines the options used to create the mesh
  63294. * @param scene defines the hosting scene
  63295. * @returns the decal mesh
  63296. * @see http://doc.babylonjs.com/how_to/decals
  63297. */
  63298. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63299. var indices = sourceMesh.getIndices();
  63300. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63301. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63302. var position = options.position || BABYLON.Vector3.Zero();
  63303. var normal = options.normal || BABYLON.Vector3.Up();
  63304. var size = options.size || BABYLON.Vector3.One();
  63305. var angle = options.angle || 0;
  63306. // Getting correct rotation
  63307. if (!normal) {
  63308. var target = new BABYLON.Vector3(0, 0, 1);
  63309. var camera = sourceMesh.getScene().activeCamera;
  63310. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63311. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63312. }
  63313. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63314. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63315. var pitch = Math.atan2(normal.y, len);
  63316. // Matrix
  63317. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63318. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63319. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63320. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63321. var vertexData = new BABYLON.VertexData();
  63322. vertexData.indices = [];
  63323. vertexData.positions = [];
  63324. vertexData.normals = [];
  63325. vertexData.uvs = [];
  63326. var currentVertexDataIndex = 0;
  63327. var extractDecalVector3 = function (indexId) {
  63328. var result = new BABYLON.PositionNormalVertex();
  63329. if (!indices || !positions || !normals) {
  63330. return result;
  63331. }
  63332. var vertexId = indices[indexId];
  63333. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63334. // Send vector to decal local world
  63335. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63336. // Get normal
  63337. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63338. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63339. return result;
  63340. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63341. var clip = function (vertices, axis) {
  63342. if (vertices.length === 0) {
  63343. return vertices;
  63344. }
  63345. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63346. var clipVertices = function (v0, v1) {
  63347. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63348. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63349. };
  63350. var result = new Array();
  63351. for (var index = 0; index < vertices.length; index += 3) {
  63352. var v1Out;
  63353. var v2Out;
  63354. var v3Out;
  63355. var total = 0;
  63356. var nV1 = null;
  63357. var nV2 = null;
  63358. var nV3 = null;
  63359. var nV4 = null;
  63360. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63361. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63362. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63363. v1Out = d1 > 0;
  63364. v2Out = d2 > 0;
  63365. v3Out = d3 > 0;
  63366. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63367. switch (total) {
  63368. case 0:
  63369. result.push(vertices[index]);
  63370. result.push(vertices[index + 1]);
  63371. result.push(vertices[index + 2]);
  63372. break;
  63373. case 1:
  63374. if (v1Out) {
  63375. nV1 = vertices[index + 1];
  63376. nV2 = vertices[index + 2];
  63377. nV3 = clipVertices(vertices[index], nV1);
  63378. nV4 = clipVertices(vertices[index], nV2);
  63379. }
  63380. if (v2Out) {
  63381. nV1 = vertices[index];
  63382. nV2 = vertices[index + 2];
  63383. nV3 = clipVertices(vertices[index + 1], nV1);
  63384. nV4 = clipVertices(vertices[index + 1], nV2);
  63385. result.push(nV3);
  63386. result.push(nV2.clone());
  63387. result.push(nV1.clone());
  63388. result.push(nV2.clone());
  63389. result.push(nV3.clone());
  63390. result.push(nV4);
  63391. break;
  63392. }
  63393. if (v3Out) {
  63394. nV1 = vertices[index];
  63395. nV2 = vertices[index + 1];
  63396. nV3 = clipVertices(vertices[index + 2], nV1);
  63397. nV4 = clipVertices(vertices[index + 2], nV2);
  63398. }
  63399. if (nV1 && nV2 && nV3 && nV4) {
  63400. result.push(nV1.clone());
  63401. result.push(nV2.clone());
  63402. result.push(nV3);
  63403. result.push(nV4);
  63404. result.push(nV3.clone());
  63405. result.push(nV2.clone());
  63406. }
  63407. break;
  63408. case 2:
  63409. if (!v1Out) {
  63410. nV1 = vertices[index].clone();
  63411. nV2 = clipVertices(nV1, vertices[index + 1]);
  63412. nV3 = clipVertices(nV1, vertices[index + 2]);
  63413. result.push(nV1);
  63414. result.push(nV2);
  63415. result.push(nV3);
  63416. }
  63417. if (!v2Out) {
  63418. nV1 = vertices[index + 1].clone();
  63419. nV2 = clipVertices(nV1, vertices[index + 2]);
  63420. nV3 = clipVertices(nV1, vertices[index]);
  63421. result.push(nV1);
  63422. result.push(nV2);
  63423. result.push(nV3);
  63424. }
  63425. if (!v3Out) {
  63426. nV1 = vertices[index + 2].clone();
  63427. nV2 = clipVertices(nV1, vertices[index]);
  63428. nV3 = clipVertices(nV1, vertices[index + 1]);
  63429. result.push(nV1);
  63430. result.push(nV2);
  63431. result.push(nV3);
  63432. }
  63433. break;
  63434. case 3:
  63435. break;
  63436. }
  63437. }
  63438. return result;
  63439. };
  63440. for (var index = 0; index < indices.length; index += 3) {
  63441. var faceVertices = new Array();
  63442. faceVertices.push(extractDecalVector3(index));
  63443. faceVertices.push(extractDecalVector3(index + 1));
  63444. faceVertices.push(extractDecalVector3(index + 2));
  63445. // Clip
  63446. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63447. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63448. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63449. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63450. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63451. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63452. if (faceVertices.length === 0) {
  63453. continue;
  63454. }
  63455. // Add UVs and get back to world
  63456. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63457. var vertex = faceVertices[vIndex];
  63458. //TODO check for Int32Array | Uint32Array | Uint16Array
  63459. vertexData.indices.push(currentVertexDataIndex);
  63460. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63461. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63462. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63463. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63464. currentVertexDataIndex++;
  63465. }
  63466. }
  63467. // Return mesh
  63468. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63469. vertexData.applyToMesh(decal);
  63470. decal.position = position.clone();
  63471. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63472. return decal;
  63473. };
  63474. // Privates
  63475. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63476. // extrusion geometry
  63477. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63478. var tangents = path3D.getTangents();
  63479. var normals = path3D.getNormals();
  63480. var binormals = path3D.getBinormals();
  63481. var distances = path3D.getDistances();
  63482. var angle = 0;
  63483. var returnScale = function () { return scale !== null ? scale : 1; };
  63484. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63485. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63486. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63487. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63488. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63489. for (var i = 0; i < curve.length; i++) {
  63490. var shapePath = new Array();
  63491. var angleStep = rotate(i, distances[i]);
  63492. var scaleRatio = scl(i, distances[i]);
  63493. for (var p = 0; p < shape.length; p++) {
  63494. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63495. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63496. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63497. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63498. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63499. shapePath[p] = rotated;
  63500. }
  63501. shapePaths[index] = shapePath;
  63502. angle += angleStep;
  63503. index++;
  63504. }
  63505. // cap
  63506. var capPath = function (shapePath) {
  63507. var pointCap = Array();
  63508. var barycenter = BABYLON.Vector3.Zero();
  63509. var i;
  63510. for (i = 0; i < shapePath.length; i++) {
  63511. barycenter.addInPlace(shapePath[i]);
  63512. }
  63513. barycenter.scaleInPlace(1.0 / shapePath.length);
  63514. for (i = 0; i < shapePath.length; i++) {
  63515. pointCap.push(barycenter);
  63516. }
  63517. return pointCap;
  63518. };
  63519. switch (cap) {
  63520. case BABYLON.Mesh.NO_CAP:
  63521. break;
  63522. case BABYLON.Mesh.CAP_START:
  63523. shapePaths[0] = capPath(shapePaths[2]);
  63524. shapePaths[1] = shapePaths[2];
  63525. break;
  63526. case BABYLON.Mesh.CAP_END:
  63527. shapePaths[index] = shapePaths[index - 1];
  63528. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63529. break;
  63530. case BABYLON.Mesh.CAP_ALL:
  63531. shapePaths[0] = capPath(shapePaths[2]);
  63532. shapePaths[1] = shapePaths[2];
  63533. shapePaths[index] = shapePaths[index - 1];
  63534. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63535. break;
  63536. default:
  63537. break;
  63538. }
  63539. return shapePaths;
  63540. };
  63541. var path3D;
  63542. var pathArray;
  63543. if (instance) { // instance update
  63544. path3D = (instance.path3D).update(curve);
  63545. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63546. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63547. return instance;
  63548. }
  63549. // extruded shape creation
  63550. path3D = new BABYLON.Path3D(curve);
  63551. var newShapePaths = new Array();
  63552. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63553. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63554. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63555. extrudedGeneric.pathArray = pathArray;
  63556. extrudedGeneric.path3D = path3D;
  63557. extrudedGeneric.cap = cap;
  63558. return extrudedGeneric;
  63559. };
  63560. return MeshBuilder;
  63561. }());
  63562. BABYLON.MeshBuilder = MeshBuilder;
  63563. })(BABYLON || (BABYLON = {}));
  63564. //# sourceMappingURL=babylon.meshBuilder.js.map
  63565. var BABYLON;
  63566. (function (BABYLON) {
  63567. /**
  63568. * Draco compression (https://google.github.io/draco/)
  63569. *
  63570. * This class wraps the Draco module.
  63571. *
  63572. * **Encoder**
  63573. *
  63574. * The encoder is not currently implemented.
  63575. *
  63576. * **Decoder**
  63577. *
  63578. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63579. *
  63580. * To update the configuration, use the following code:
  63581. * ```javascript
  63582. * BABYLON.DracoCompression.Configuration = {
  63583. * decoder: {
  63584. * wasmUrl: "<url to the WebAssembly library>",
  63585. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63586. * fallbackUrl: "<url to the fallback JavaScript library>",
  63587. * }
  63588. * };
  63589. * ```
  63590. *
  63591. * 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.
  63592. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63593. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63594. *
  63595. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63596. * ```javascript
  63597. * var dracoCompression = new BABYLON.DracoCompression();
  63598. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63599. * [BABYLON.VertexBuffer.PositionKind]: 0
  63600. * });
  63601. * ```
  63602. *
  63603. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63604. */
  63605. var DracoCompression = /** @class */ (function () {
  63606. /**
  63607. * Constructor
  63608. */
  63609. function DracoCompression() {
  63610. }
  63611. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63612. /**
  63613. * Returns true if the decoder is available.
  63614. */
  63615. get: function () {
  63616. if (typeof DracoDecoderModule !== "undefined") {
  63617. return true;
  63618. }
  63619. var decoder = DracoCompression.Configuration.decoder;
  63620. if (decoder) {
  63621. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63622. return true;
  63623. }
  63624. if (decoder.fallbackUrl) {
  63625. return true;
  63626. }
  63627. }
  63628. return false;
  63629. },
  63630. enumerable: true,
  63631. configurable: true
  63632. });
  63633. /**
  63634. * Stop all async operations and release resources.
  63635. */
  63636. DracoCompression.prototype.dispose = function () {
  63637. };
  63638. /**
  63639. * Decode Draco compressed mesh data to vertex data.
  63640. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63641. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63642. * @returns A promise that resolves with the decoded vertex data
  63643. */
  63644. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63645. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63646. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63647. var module = wrappedModule.module;
  63648. var vertexData = new BABYLON.VertexData();
  63649. var buffer = new module.DecoderBuffer();
  63650. buffer.Init(dataView, dataView.byteLength);
  63651. var decoder = new module.Decoder();
  63652. var geometry;
  63653. var status;
  63654. try {
  63655. var type = decoder.GetEncodedGeometryType(buffer);
  63656. switch (type) {
  63657. case module.TRIANGULAR_MESH:
  63658. geometry = new module.Mesh();
  63659. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63660. break;
  63661. case module.POINT_CLOUD:
  63662. geometry = new module.PointCloud();
  63663. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63664. break;
  63665. default:
  63666. throw new Error("Invalid geometry type " + type);
  63667. }
  63668. if (!status.ok() || !geometry.ptr) {
  63669. throw new Error(status.error_msg());
  63670. }
  63671. var numPoints = geometry.num_points();
  63672. if (type === module.TRIANGULAR_MESH) {
  63673. var numFaces = geometry.num_faces();
  63674. var faceIndices = new module.DracoInt32Array();
  63675. try {
  63676. var indices = new Uint32Array(numFaces * 3);
  63677. for (var i = 0; i < numFaces; i++) {
  63678. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63679. var offset = i * 3;
  63680. indices[offset + 0] = faceIndices.GetValue(0);
  63681. indices[offset + 1] = faceIndices.GetValue(1);
  63682. indices[offset + 2] = faceIndices.GetValue(2);
  63683. }
  63684. vertexData.indices = indices;
  63685. }
  63686. finally {
  63687. module.destroy(faceIndices);
  63688. }
  63689. }
  63690. for (var kind in attributes) {
  63691. var uniqueId = attributes[kind];
  63692. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63693. var dracoData = new module.DracoFloat32Array();
  63694. try {
  63695. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63696. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63697. for (var i = 0; i < babylonData.length; i++) {
  63698. babylonData[i] = dracoData.GetValue(i);
  63699. }
  63700. vertexData.set(babylonData, kind);
  63701. }
  63702. finally {
  63703. module.destroy(dracoData);
  63704. }
  63705. }
  63706. }
  63707. finally {
  63708. if (geometry) {
  63709. module.destroy(geometry);
  63710. }
  63711. module.destroy(decoder);
  63712. module.destroy(buffer);
  63713. }
  63714. return vertexData;
  63715. });
  63716. };
  63717. DracoCompression._GetDecoderModule = function () {
  63718. if (!DracoCompression._DecoderModulePromise) {
  63719. var promise = null;
  63720. var config_1 = {};
  63721. if (typeof DracoDecoderModule !== "undefined") {
  63722. promise = Promise.resolve();
  63723. }
  63724. else {
  63725. var decoder = DracoCompression.Configuration.decoder;
  63726. if (decoder) {
  63727. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63728. promise = Promise.all([
  63729. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63730. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63731. config_1.wasmBinary = data;
  63732. })
  63733. ]);
  63734. }
  63735. else if (decoder.fallbackUrl) {
  63736. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63737. }
  63738. }
  63739. }
  63740. if (!promise) {
  63741. throw new Error("Draco decoder module is not available");
  63742. }
  63743. DracoCompression._DecoderModulePromise = promise.then(function () {
  63744. return new Promise(function (resolve) {
  63745. config_1.onModuleLoaded = function (decoderModule) {
  63746. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63747. resolve({ module: decoderModule });
  63748. };
  63749. DracoDecoderModule(config_1);
  63750. });
  63751. });
  63752. }
  63753. return DracoCompression._DecoderModulePromise;
  63754. };
  63755. DracoCompression._LoadScriptAsync = function (url) {
  63756. return new Promise(function (resolve, reject) {
  63757. BABYLON.Tools.LoadScript(url, function () {
  63758. resolve();
  63759. }, function (message) {
  63760. reject(new Error(message));
  63761. });
  63762. });
  63763. };
  63764. DracoCompression._LoadFileAsync = function (url) {
  63765. return new Promise(function (resolve, reject) {
  63766. BABYLON.Tools.LoadFile(url, function (data) {
  63767. resolve(data);
  63768. }, undefined, undefined, true, function (request, exception) {
  63769. reject(exception);
  63770. });
  63771. });
  63772. };
  63773. /**
  63774. * The configuration. Defaults to the following urls:
  63775. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63776. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63777. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63778. */
  63779. DracoCompression.Configuration = {
  63780. decoder: {
  63781. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63782. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63783. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63784. }
  63785. };
  63786. return DracoCompression;
  63787. }());
  63788. BABYLON.DracoCompression = DracoCompression;
  63789. })(BABYLON || (BABYLON = {}));
  63790. //# sourceMappingURL=babylon.dracoCompression.js.map
  63791. var BABYLON;
  63792. (function (BABYLON) {
  63793. var AudioEngine = /** @class */ (function () {
  63794. function AudioEngine() {
  63795. this._audioContext = null;
  63796. this._audioContextInitialized = false;
  63797. this.canUseWebAudio = false;
  63798. this.WarnedWebAudioUnsupported = false;
  63799. this.unlocked = false;
  63800. this.isMP3supported = false;
  63801. this.isOGGsupported = false;
  63802. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63803. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63804. this.canUseWebAudio = true;
  63805. }
  63806. var audioElem = document.createElement('audio');
  63807. try {
  63808. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63809. this.isMP3supported = true;
  63810. }
  63811. }
  63812. catch (e) {
  63813. // protect error during capability check.
  63814. }
  63815. try {
  63816. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63817. this.isOGGsupported = true;
  63818. }
  63819. }
  63820. catch (e) {
  63821. // protect error during capability check.
  63822. }
  63823. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63824. this._unlockiOSaudio();
  63825. }
  63826. else {
  63827. this.unlocked = true;
  63828. }
  63829. }
  63830. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63831. get: function () {
  63832. if (!this._audioContextInitialized) {
  63833. this._initializeAudioContext();
  63834. }
  63835. return this._audioContext;
  63836. },
  63837. enumerable: true,
  63838. configurable: true
  63839. });
  63840. AudioEngine.prototype._unlockiOSaudio = function () {
  63841. var _this = this;
  63842. var unlockaudio = function () {
  63843. if (!_this.audioContext) {
  63844. return;
  63845. }
  63846. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63847. var source = _this.audioContext.createBufferSource();
  63848. source.buffer = buffer;
  63849. source.connect(_this.audioContext.destination);
  63850. source.start(0);
  63851. setTimeout(function () {
  63852. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63853. _this.unlocked = true;
  63854. window.removeEventListener('touchend', unlockaudio, false);
  63855. if (_this.onAudioUnlocked) {
  63856. _this.onAudioUnlocked();
  63857. }
  63858. }
  63859. }, 0);
  63860. };
  63861. window.addEventListener('touchend', unlockaudio, false);
  63862. };
  63863. AudioEngine.prototype._initializeAudioContext = function () {
  63864. try {
  63865. if (this.canUseWebAudio) {
  63866. this._audioContext = new AudioContext();
  63867. // create a global volume gain node
  63868. this.masterGain = this._audioContext.createGain();
  63869. this.masterGain.gain.value = 1;
  63870. this.masterGain.connect(this._audioContext.destination);
  63871. this._audioContextInitialized = true;
  63872. }
  63873. }
  63874. catch (e) {
  63875. this.canUseWebAudio = false;
  63876. BABYLON.Tools.Error("Web Audio: " + e.message);
  63877. }
  63878. };
  63879. AudioEngine.prototype.dispose = function () {
  63880. if (this.canUseWebAudio && this._audioContextInitialized) {
  63881. if (this._connectedAnalyser && this._audioContext) {
  63882. this._connectedAnalyser.stopDebugCanvas();
  63883. this._connectedAnalyser.dispose();
  63884. this.masterGain.disconnect();
  63885. this.masterGain.connect(this._audioContext.destination);
  63886. this._connectedAnalyser = null;
  63887. }
  63888. this.masterGain.gain.value = 1;
  63889. }
  63890. this.WarnedWebAudioUnsupported = false;
  63891. };
  63892. AudioEngine.prototype.getGlobalVolume = function () {
  63893. if (this.canUseWebAudio && this._audioContextInitialized) {
  63894. return this.masterGain.gain.value;
  63895. }
  63896. else {
  63897. return -1;
  63898. }
  63899. };
  63900. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  63901. if (this.canUseWebAudio && this._audioContextInitialized) {
  63902. this.masterGain.gain.value = newVolume;
  63903. }
  63904. };
  63905. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  63906. if (this._connectedAnalyser) {
  63907. this._connectedAnalyser.stopDebugCanvas();
  63908. }
  63909. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  63910. this._connectedAnalyser = analyser;
  63911. this.masterGain.disconnect();
  63912. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  63913. }
  63914. };
  63915. return AudioEngine;
  63916. }());
  63917. BABYLON.AudioEngine = AudioEngine;
  63918. })(BABYLON || (BABYLON = {}));
  63919. //# sourceMappingURL=babylon.audioEngine.js.map
  63920. var BABYLON;
  63921. (function (BABYLON) {
  63922. var Sound = /** @class */ (function () {
  63923. /**
  63924. * Create a sound and attach it to a scene
  63925. * @param name Name of your sound
  63926. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  63927. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  63928. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  63929. */
  63930. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  63931. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  63932. var _this = this;
  63933. this.autoplay = false;
  63934. this.loop = false;
  63935. this.useCustomAttenuation = false;
  63936. this.spatialSound = false;
  63937. this.refDistance = 1;
  63938. this.rolloffFactor = 1;
  63939. this.maxDistance = 100;
  63940. this.distanceModel = "linear";
  63941. this._panningModel = "equalpower";
  63942. /**
  63943. * Observable event when the current playing sound finishes.
  63944. */
  63945. this.onEndedObservable = new BABYLON.Observable();
  63946. this._playbackRate = 1;
  63947. this._streaming = false;
  63948. this._startTime = 0;
  63949. this._startOffset = 0;
  63950. this._position = BABYLON.Vector3.Zero();
  63951. /** @hidden */
  63952. this._positionInEmitterSpace = false;
  63953. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  63954. this._volume = 1;
  63955. this._isReadyToPlay = false;
  63956. this.isPlaying = false;
  63957. this.isPaused = false;
  63958. this._isDirectional = false;
  63959. // Used if you'd like to create a directional sound.
  63960. // If not set, the sound will be omnidirectional
  63961. this._coneInnerAngle = 360;
  63962. this._coneOuterAngle = 360;
  63963. this._coneOuterGain = 0;
  63964. this._isOutputConnected = false;
  63965. this._urlType = "Unknown";
  63966. this.name = name;
  63967. this._scene = scene;
  63968. this._readyToPlayCallback = readyToPlayCallback;
  63969. // Default custom attenuation function is a linear attenuation
  63970. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  63971. if (currentDistance < maxDistance) {
  63972. return currentVolume * (1 - currentDistance / maxDistance);
  63973. }
  63974. else {
  63975. return 0;
  63976. }
  63977. };
  63978. if (options) {
  63979. this.autoplay = options.autoplay || false;
  63980. this.loop = options.loop || false;
  63981. // if volume === 0, we need another way to check this option
  63982. if (options.volume !== undefined) {
  63983. this._volume = options.volume;
  63984. }
  63985. this.spatialSound = options.spatialSound || false;
  63986. this.maxDistance = options.maxDistance || 100;
  63987. this.useCustomAttenuation = options.useCustomAttenuation || false;
  63988. this.rolloffFactor = options.rolloffFactor || 1;
  63989. this.refDistance = options.refDistance || 1;
  63990. this.distanceModel = options.distanceModel || "linear";
  63991. this._playbackRate = options.playbackRate || 1;
  63992. this._streaming = options.streaming || false;
  63993. }
  63994. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63995. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  63996. this._soundGain.gain.value = this._volume;
  63997. this._inputAudioNode = this._soundGain;
  63998. this._outputAudioNode = this._soundGain;
  63999. if (this.spatialSound) {
  64000. this._createSpatialParameters();
  64001. }
  64002. this._scene.mainSoundTrack.AddSound(this);
  64003. var validParameter = true;
  64004. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64005. if (urlOrArrayBuffer) {
  64006. try {
  64007. if (typeof (urlOrArrayBuffer) === "string") {
  64008. this._urlType = "String";
  64009. }
  64010. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64011. this._urlType = "ArrayBuffer";
  64012. }
  64013. else if (urlOrArrayBuffer instanceof MediaStream) {
  64014. this._urlType = "MediaStream";
  64015. }
  64016. else if (Array.isArray(urlOrArrayBuffer)) {
  64017. this._urlType = "Array";
  64018. }
  64019. var urls = [];
  64020. var codecSupportedFound = false;
  64021. switch (this._urlType) {
  64022. case "MediaStream":
  64023. this._streaming = true;
  64024. this._isReadyToPlay = true;
  64025. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  64026. if (this.autoplay) {
  64027. this.play();
  64028. }
  64029. if (this._readyToPlayCallback) {
  64030. this._readyToPlayCallback();
  64031. }
  64032. break;
  64033. case "ArrayBuffer":
  64034. if (urlOrArrayBuffer.byteLength > 0) {
  64035. codecSupportedFound = true;
  64036. this._soundLoaded(urlOrArrayBuffer);
  64037. }
  64038. break;
  64039. case "String":
  64040. urls.push(urlOrArrayBuffer);
  64041. case "Array":
  64042. if (urls.length === 0)
  64043. urls = urlOrArrayBuffer;
  64044. // If we found a supported format, we load it immediately and stop the loop
  64045. for (var i = 0; i < urls.length; i++) {
  64046. var url = urls[i];
  64047. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64048. codecSupportedFound = true;
  64049. }
  64050. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64051. codecSupportedFound = true;
  64052. }
  64053. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64054. codecSupportedFound = true;
  64055. }
  64056. if (url.indexOf("blob:") !== -1) {
  64057. codecSupportedFound = true;
  64058. }
  64059. if (codecSupportedFound) {
  64060. // Loading sound using XHR2
  64061. if (!this._streaming) {
  64062. this._scene._loadFile(url, function (data) {
  64063. _this._soundLoaded(data);
  64064. }, undefined, true, true, function (exception) {
  64065. if (exception) {
  64066. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64067. }
  64068. BABYLON.Tools.Error("Sound creation aborted.");
  64069. _this._scene.mainSoundTrack.RemoveSound(_this);
  64070. });
  64071. }
  64072. // Streaming sound using HTML5 Audio tag
  64073. else {
  64074. this._htmlAudioElement = new Audio(url);
  64075. this._htmlAudioElement.controls = false;
  64076. this._htmlAudioElement.loop = this.loop;
  64077. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  64078. this._htmlAudioElement.preload = "auto";
  64079. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  64080. _this._isReadyToPlay = true;
  64081. if (_this.autoplay) {
  64082. _this.play();
  64083. }
  64084. if (_this._readyToPlayCallback) {
  64085. _this._readyToPlayCallback();
  64086. }
  64087. });
  64088. document.body.appendChild(this._htmlAudioElement);
  64089. }
  64090. break;
  64091. }
  64092. }
  64093. break;
  64094. default:
  64095. validParameter = false;
  64096. break;
  64097. }
  64098. if (!validParameter) {
  64099. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  64100. }
  64101. else {
  64102. if (!codecSupportedFound) {
  64103. this._isReadyToPlay = true;
  64104. // Simulating a ready to play event to avoid breaking code path
  64105. if (this._readyToPlayCallback) {
  64106. window.setTimeout(function () {
  64107. if (_this._readyToPlayCallback) {
  64108. _this._readyToPlayCallback();
  64109. }
  64110. }, 1000);
  64111. }
  64112. }
  64113. }
  64114. }
  64115. catch (ex) {
  64116. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  64117. this._scene.mainSoundTrack.RemoveSound(this);
  64118. }
  64119. }
  64120. }
  64121. else {
  64122. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  64123. this._scene.mainSoundTrack.AddSound(this);
  64124. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  64125. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  64126. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  64127. }
  64128. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  64129. if (this._readyToPlayCallback) {
  64130. window.setTimeout(function () {
  64131. if (_this._readyToPlayCallback) {
  64132. _this._readyToPlayCallback();
  64133. }
  64134. }, 1000);
  64135. }
  64136. }
  64137. }
  64138. Sound.prototype.dispose = function () {
  64139. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64140. if (this.isPlaying) {
  64141. this.stop();
  64142. }
  64143. this._isReadyToPlay = false;
  64144. if (this.soundTrackId === -1) {
  64145. this._scene.mainSoundTrack.RemoveSound(this);
  64146. }
  64147. else {
  64148. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  64149. }
  64150. if (this._soundGain) {
  64151. this._soundGain.disconnect();
  64152. this._soundGain = null;
  64153. }
  64154. if (this._soundPanner) {
  64155. this._soundPanner.disconnect();
  64156. this._soundPanner = null;
  64157. }
  64158. if (this._soundSource) {
  64159. this._soundSource.disconnect();
  64160. this._soundSource = null;
  64161. }
  64162. this._audioBuffer = null;
  64163. if (this._htmlAudioElement) {
  64164. this._htmlAudioElement.pause();
  64165. this._htmlAudioElement.src = "";
  64166. document.body.removeChild(this._htmlAudioElement);
  64167. }
  64168. if (this._streamingSource) {
  64169. this._streamingSource.disconnect();
  64170. }
  64171. if (this._connectedMesh && this._registerFunc) {
  64172. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64173. this._connectedMesh = null;
  64174. }
  64175. }
  64176. };
  64177. Sound.prototype.isReady = function () {
  64178. return this._isReadyToPlay;
  64179. };
  64180. Sound.prototype._soundLoaded = function (audioData) {
  64181. var _this = this;
  64182. if (!BABYLON.Engine.audioEngine.audioContext) {
  64183. return;
  64184. }
  64185. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  64186. _this._audioBuffer = buffer;
  64187. _this._isReadyToPlay = true;
  64188. if (_this.autoplay) {
  64189. _this.play();
  64190. }
  64191. if (_this._readyToPlayCallback) {
  64192. _this._readyToPlayCallback();
  64193. }
  64194. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  64195. };
  64196. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  64197. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64198. this._audioBuffer = audioBuffer;
  64199. this._isReadyToPlay = true;
  64200. }
  64201. };
  64202. Sound.prototype.updateOptions = function (options) {
  64203. if (options) {
  64204. this.loop = options.loop || this.loop;
  64205. this.maxDistance = options.maxDistance || this.maxDistance;
  64206. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  64207. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  64208. this.refDistance = options.refDistance || this.refDistance;
  64209. this.distanceModel = options.distanceModel || this.distanceModel;
  64210. this._playbackRate = options.playbackRate || this._playbackRate;
  64211. this._updateSpatialParameters();
  64212. if (this.isPlaying) {
  64213. if (this._streaming && this._htmlAudioElement) {
  64214. this._htmlAudioElement.playbackRate = this._playbackRate;
  64215. }
  64216. else {
  64217. if (this._soundSource) {
  64218. this._soundSource.playbackRate.value = this._playbackRate;
  64219. }
  64220. }
  64221. }
  64222. }
  64223. };
  64224. Sound.prototype._createSpatialParameters = function () {
  64225. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64226. if (this._scene.headphone) {
  64227. this._panningModel = "HRTF";
  64228. }
  64229. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  64230. this._updateSpatialParameters();
  64231. this._soundPanner.connect(this._outputAudioNode);
  64232. this._inputAudioNode = this._soundPanner;
  64233. }
  64234. };
  64235. Sound.prototype._updateSpatialParameters = function () {
  64236. if (this.spatialSound && this._soundPanner) {
  64237. if (this.useCustomAttenuation) {
  64238. // Tricks to disable in a way embedded Web Audio attenuation
  64239. this._soundPanner.distanceModel = "linear";
  64240. this._soundPanner.maxDistance = Number.MAX_VALUE;
  64241. this._soundPanner.refDistance = 1;
  64242. this._soundPanner.rolloffFactor = 1;
  64243. this._soundPanner.panningModel = this._panningModel;
  64244. }
  64245. else {
  64246. this._soundPanner.distanceModel = this.distanceModel;
  64247. this._soundPanner.maxDistance = this.maxDistance;
  64248. this._soundPanner.refDistance = this.refDistance;
  64249. this._soundPanner.rolloffFactor = this.rolloffFactor;
  64250. this._soundPanner.panningModel = this._panningModel;
  64251. }
  64252. }
  64253. };
  64254. Sound.prototype.switchPanningModelToHRTF = function () {
  64255. this._panningModel = "HRTF";
  64256. this._switchPanningModel();
  64257. };
  64258. Sound.prototype.switchPanningModelToEqualPower = function () {
  64259. this._panningModel = "equalpower";
  64260. this._switchPanningModel();
  64261. };
  64262. Sound.prototype._switchPanningModel = function () {
  64263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64264. this._soundPanner.panningModel = this._panningModel;
  64265. }
  64266. };
  64267. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  64268. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64269. if (this._isOutputConnected) {
  64270. this._outputAudioNode.disconnect();
  64271. }
  64272. this._outputAudioNode.connect(soundTrackAudioNode);
  64273. this._isOutputConnected = true;
  64274. }
  64275. };
  64276. /**
  64277. * Transform this sound into a directional source
  64278. * @param coneInnerAngle Size of the inner cone in degree
  64279. * @param coneOuterAngle Size of the outer cone in degree
  64280. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  64281. */
  64282. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  64283. if (coneOuterAngle < coneInnerAngle) {
  64284. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  64285. return;
  64286. }
  64287. this._coneInnerAngle = coneInnerAngle;
  64288. this._coneOuterAngle = coneOuterAngle;
  64289. this._coneOuterGain = coneOuterGain;
  64290. this._isDirectional = true;
  64291. if (this.isPlaying && this.loop) {
  64292. this.stop();
  64293. this.play();
  64294. }
  64295. };
  64296. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  64297. /**
  64298. * Gets or sets the inner angle for the directional cone.
  64299. */
  64300. get: function () {
  64301. return this._coneInnerAngle;
  64302. },
  64303. /**
  64304. * Gets or sets the inner angle for the directional cone.
  64305. */
  64306. set: function (value) {
  64307. if (value != this._coneInnerAngle) {
  64308. if (this._coneOuterAngle < value) {
  64309. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64310. return;
  64311. }
  64312. this._coneInnerAngle = value;
  64313. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64314. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64315. }
  64316. }
  64317. },
  64318. enumerable: true,
  64319. configurable: true
  64320. });
  64321. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  64322. /**
  64323. * Gets or sets the outer angle for the directional cone.
  64324. */
  64325. get: function () {
  64326. return this._coneOuterAngle;
  64327. },
  64328. /**
  64329. * Gets or sets the outer angle for the directional cone.
  64330. */
  64331. set: function (value) {
  64332. if (value != this._coneOuterAngle) {
  64333. if (value < this._coneInnerAngle) {
  64334. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64335. return;
  64336. }
  64337. this._coneOuterAngle = value;
  64338. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64339. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64340. }
  64341. }
  64342. },
  64343. enumerable: true,
  64344. configurable: true
  64345. });
  64346. Sound.prototype.setPosition = function (newPosition) {
  64347. this._position = newPosition;
  64348. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  64349. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64350. }
  64351. };
  64352. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  64353. this._localDirection = newLocalDirection;
  64354. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  64355. this._updateDirection();
  64356. }
  64357. };
  64358. Sound.prototype._updateDirection = function () {
  64359. if (!this._connectedMesh || !this._soundPanner) {
  64360. return;
  64361. }
  64362. var mat = this._connectedMesh.getWorldMatrix();
  64363. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  64364. direction.normalize();
  64365. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  64366. };
  64367. Sound.prototype.updateDistanceFromListener = function () {
  64368. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64369. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64370. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64371. }
  64372. };
  64373. Sound.prototype.setAttenuationFunction = function (callback) {
  64374. this._customAttenuationFunction = callback;
  64375. };
  64376. /**
  64377. * Play the sound
  64378. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64379. * @param offset (optional) Start the sound setting it at a specific time
  64380. */
  64381. Sound.prototype.play = function (time, offset) {
  64382. var _this = this;
  64383. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64384. try {
  64385. if (this._startOffset < 0) {
  64386. time = -this._startOffset;
  64387. this._startOffset = 0;
  64388. }
  64389. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64390. if (!this._soundSource || !this._streamingSource) {
  64391. if (this.spatialSound && this._soundPanner) {
  64392. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  64393. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64394. }
  64395. if (this._isDirectional) {
  64396. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64397. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64398. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64399. if (this._connectedMesh) {
  64400. this._updateDirection();
  64401. }
  64402. else {
  64403. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64404. }
  64405. }
  64406. }
  64407. }
  64408. if (this._streaming) {
  64409. if (!this._streamingSource) {
  64410. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64411. this._htmlAudioElement.onended = function () { _this._onended(); };
  64412. this._htmlAudioElement.playbackRate = this._playbackRate;
  64413. }
  64414. this._streamingSource.disconnect();
  64415. this._streamingSource.connect(this._inputAudioNode);
  64416. if (this._htmlAudioElement) {
  64417. this._htmlAudioElement.play();
  64418. }
  64419. }
  64420. else {
  64421. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64422. this._soundSource.buffer = this._audioBuffer;
  64423. this._soundSource.connect(this._inputAudioNode);
  64424. this._soundSource.loop = this.loop;
  64425. this._soundSource.playbackRate.value = this._playbackRate;
  64426. this._soundSource.onended = function () { _this._onended(); };
  64427. if (this._soundSource.buffer) {
  64428. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64429. }
  64430. }
  64431. this._startTime = startTime;
  64432. this.isPlaying = true;
  64433. this.isPaused = false;
  64434. }
  64435. catch (ex) {
  64436. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64437. }
  64438. }
  64439. };
  64440. Sound.prototype._onended = function () {
  64441. this.isPlaying = false;
  64442. if (this.onended) {
  64443. this.onended();
  64444. }
  64445. this.onEndedObservable.notifyObservers(this);
  64446. };
  64447. /**
  64448. * Stop the sound
  64449. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64450. */
  64451. Sound.prototype.stop = function (time) {
  64452. if (this.isPlaying) {
  64453. if (this._streaming) {
  64454. if (this._htmlAudioElement) {
  64455. this._htmlAudioElement.pause();
  64456. // Test needed for Firefox or it will generate an Invalid State Error
  64457. if (this._htmlAudioElement.currentTime > 0) {
  64458. this._htmlAudioElement.currentTime = 0;
  64459. }
  64460. }
  64461. else {
  64462. this._streamingSource.disconnect();
  64463. }
  64464. }
  64465. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64466. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64467. this._soundSource.stop(stopTime);
  64468. this._soundSource.onended = function () { };
  64469. if (!this.isPaused) {
  64470. this._startOffset = 0;
  64471. }
  64472. }
  64473. this.isPlaying = false;
  64474. }
  64475. };
  64476. Sound.prototype.pause = function () {
  64477. if (this.isPlaying) {
  64478. this.isPaused = true;
  64479. if (this._streaming) {
  64480. if (this._htmlAudioElement) {
  64481. this._htmlAudioElement.pause();
  64482. }
  64483. else {
  64484. this._streamingSource.disconnect();
  64485. }
  64486. }
  64487. else if (BABYLON.Engine.audioEngine.audioContext) {
  64488. this.stop(0);
  64489. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64490. }
  64491. }
  64492. };
  64493. Sound.prototype.setVolume = function (newVolume, time) {
  64494. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64495. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64496. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64497. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64498. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64499. }
  64500. else {
  64501. this._soundGain.gain.value = newVolume;
  64502. }
  64503. }
  64504. this._volume = newVolume;
  64505. };
  64506. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64507. this._playbackRate = newPlaybackRate;
  64508. if (this.isPlaying) {
  64509. if (this._streaming && this._htmlAudioElement) {
  64510. this._htmlAudioElement.playbackRate = this._playbackRate;
  64511. }
  64512. else if (this._soundSource) {
  64513. this._soundSource.playbackRate.value = this._playbackRate;
  64514. }
  64515. }
  64516. };
  64517. Sound.prototype.getVolume = function () {
  64518. return this._volume;
  64519. };
  64520. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64521. var _this = this;
  64522. if (this._connectedMesh && this._registerFunc) {
  64523. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64524. this._registerFunc = null;
  64525. }
  64526. this._connectedMesh = meshToConnectTo;
  64527. if (!this.spatialSound) {
  64528. this.spatialSound = true;
  64529. this._createSpatialParameters();
  64530. if (this.isPlaying && this.loop) {
  64531. this.stop();
  64532. this.play();
  64533. }
  64534. }
  64535. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64536. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64537. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64538. };
  64539. Sound.prototype.detachFromMesh = function () {
  64540. if (this._connectedMesh && this._registerFunc) {
  64541. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64542. this._registerFunc = null;
  64543. this._connectedMesh = null;
  64544. }
  64545. };
  64546. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64547. if (!node.getBoundingInfo) {
  64548. return;
  64549. }
  64550. var mesh = node;
  64551. if (this._positionInEmitterSpace) {
  64552. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  64553. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  64554. }
  64555. else {
  64556. var boundingInfo = mesh.getBoundingInfo();
  64557. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64558. }
  64559. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64560. this._updateDirection();
  64561. }
  64562. };
  64563. Sound.prototype.clone = function () {
  64564. var _this = this;
  64565. if (!this._streaming) {
  64566. var setBufferAndRun = function () {
  64567. if (_this._isReadyToPlay) {
  64568. clonedSound._audioBuffer = _this.getAudioBuffer();
  64569. clonedSound._isReadyToPlay = true;
  64570. if (clonedSound.autoplay) {
  64571. clonedSound.play();
  64572. }
  64573. }
  64574. else {
  64575. window.setTimeout(setBufferAndRun, 300);
  64576. }
  64577. };
  64578. var currentOptions = {
  64579. autoplay: this.autoplay, loop: this.loop,
  64580. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64581. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64582. refDistance: this.refDistance, distanceModel: this.distanceModel
  64583. };
  64584. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64585. if (this.useCustomAttenuation) {
  64586. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64587. }
  64588. clonedSound.setPosition(this._position);
  64589. clonedSound.setPlaybackRate(this._playbackRate);
  64590. setBufferAndRun();
  64591. return clonedSound;
  64592. }
  64593. // Can't clone a streaming sound
  64594. else {
  64595. return null;
  64596. }
  64597. };
  64598. Sound.prototype.getAudioBuffer = function () {
  64599. return this._audioBuffer;
  64600. };
  64601. Sound.prototype.serialize = function () {
  64602. var serializationObject = {
  64603. name: this.name,
  64604. url: this.name,
  64605. autoplay: this.autoplay,
  64606. loop: this.loop,
  64607. volume: this._volume,
  64608. spatialSound: this.spatialSound,
  64609. maxDistance: this.maxDistance,
  64610. rolloffFactor: this.rolloffFactor,
  64611. refDistance: this.refDistance,
  64612. distanceModel: this.distanceModel,
  64613. playbackRate: this._playbackRate,
  64614. panningModel: this._panningModel,
  64615. soundTrackId: this.soundTrackId
  64616. };
  64617. if (this.spatialSound) {
  64618. if (this._connectedMesh)
  64619. serializationObject.connectedMeshId = this._connectedMesh.id;
  64620. serializationObject.position = this._position.asArray();
  64621. serializationObject.refDistance = this.refDistance;
  64622. serializationObject.distanceModel = this.distanceModel;
  64623. serializationObject.isDirectional = this._isDirectional;
  64624. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64625. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64626. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64627. serializationObject.coneOuterGain = this._coneOuterGain;
  64628. }
  64629. return serializationObject;
  64630. };
  64631. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  64632. var soundName = parsedSound.name;
  64633. var soundUrl;
  64634. if (parsedSound.url) {
  64635. soundUrl = rootUrl + parsedSound.url;
  64636. }
  64637. else {
  64638. soundUrl = rootUrl + soundName;
  64639. }
  64640. var options = {
  64641. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  64642. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  64643. rolloffFactor: parsedSound.rolloffFactor,
  64644. refDistance: parsedSound.refDistance,
  64645. distanceModel: parsedSound.distanceModel,
  64646. playbackRate: parsedSound.playbackRate
  64647. };
  64648. var newSound;
  64649. if (!sourceSound) {
  64650. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  64651. scene._addPendingData(newSound);
  64652. }
  64653. else {
  64654. var setBufferAndRun = function () {
  64655. if (sourceSound._isReadyToPlay) {
  64656. newSound._audioBuffer = sourceSound.getAudioBuffer();
  64657. newSound._isReadyToPlay = true;
  64658. if (newSound.autoplay) {
  64659. newSound.play();
  64660. }
  64661. }
  64662. else {
  64663. window.setTimeout(setBufferAndRun, 300);
  64664. }
  64665. };
  64666. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  64667. setBufferAndRun();
  64668. }
  64669. if (parsedSound.position) {
  64670. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  64671. newSound.setPosition(soundPosition);
  64672. }
  64673. if (parsedSound.isDirectional) {
  64674. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  64675. if (parsedSound.localDirectionToMesh) {
  64676. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  64677. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  64678. }
  64679. }
  64680. if (parsedSound.connectedMeshId) {
  64681. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  64682. if (connectedMesh) {
  64683. newSound.attachToMesh(connectedMesh);
  64684. }
  64685. }
  64686. return newSound;
  64687. };
  64688. return Sound;
  64689. }());
  64690. BABYLON.Sound = Sound;
  64691. })(BABYLON || (BABYLON = {}));
  64692. //# sourceMappingURL=babylon.sound.js.map
  64693. var BABYLON;
  64694. (function (BABYLON) {
  64695. var SoundTrack = /** @class */ (function () {
  64696. function SoundTrack(scene, options) {
  64697. this.id = -1;
  64698. this._isMainTrack = false;
  64699. this._isInitialized = false;
  64700. this._scene = scene;
  64701. this.soundCollection = new Array();
  64702. this._options = options;
  64703. if (!this._isMainTrack) {
  64704. this._scene.soundTracks.push(this);
  64705. this.id = this._scene.soundTracks.length - 1;
  64706. }
  64707. }
  64708. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64709. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64710. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64711. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64712. if (this._options) {
  64713. if (this._options.volume) {
  64714. this._outputAudioNode.gain.value = this._options.volume;
  64715. }
  64716. if (this._options.mainTrack) {
  64717. this._isMainTrack = this._options.mainTrack;
  64718. }
  64719. }
  64720. this._isInitialized = true;
  64721. }
  64722. };
  64723. SoundTrack.prototype.dispose = function () {
  64724. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64725. if (this._connectedAnalyser) {
  64726. this._connectedAnalyser.stopDebugCanvas();
  64727. }
  64728. while (this.soundCollection.length) {
  64729. this.soundCollection[0].dispose();
  64730. }
  64731. if (this._outputAudioNode) {
  64732. this._outputAudioNode.disconnect();
  64733. }
  64734. this._outputAudioNode = null;
  64735. }
  64736. };
  64737. SoundTrack.prototype.AddSound = function (sound) {
  64738. if (!this._isInitialized) {
  64739. this._initializeSoundTrackAudioGraph();
  64740. }
  64741. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64742. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64743. }
  64744. if (sound.soundTrackId) {
  64745. if (sound.soundTrackId === -1) {
  64746. this._scene.mainSoundTrack.RemoveSound(sound);
  64747. }
  64748. else {
  64749. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64750. }
  64751. }
  64752. this.soundCollection.push(sound);
  64753. sound.soundTrackId = this.id;
  64754. };
  64755. SoundTrack.prototype.RemoveSound = function (sound) {
  64756. var index = this.soundCollection.indexOf(sound);
  64757. if (index !== -1) {
  64758. this.soundCollection.splice(index, 1);
  64759. }
  64760. };
  64761. SoundTrack.prototype.setVolume = function (newVolume) {
  64762. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64763. this._outputAudioNode.gain.value = newVolume;
  64764. }
  64765. };
  64766. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64767. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64768. for (var i = 0; i < this.soundCollection.length; i++) {
  64769. this.soundCollection[i].switchPanningModelToHRTF();
  64770. }
  64771. }
  64772. };
  64773. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64774. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64775. for (var i = 0; i < this.soundCollection.length; i++) {
  64776. this.soundCollection[i].switchPanningModelToEqualPower();
  64777. }
  64778. }
  64779. };
  64780. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64781. if (this._connectedAnalyser) {
  64782. this._connectedAnalyser.stopDebugCanvas();
  64783. }
  64784. this._connectedAnalyser = analyser;
  64785. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64786. this._outputAudioNode.disconnect();
  64787. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64788. }
  64789. };
  64790. return SoundTrack;
  64791. }());
  64792. BABYLON.SoundTrack = SoundTrack;
  64793. })(BABYLON || (BABYLON = {}));
  64794. //# sourceMappingURL=babylon.soundtrack.js.map
  64795. var BABYLON;
  64796. (function (BABYLON) {
  64797. /**
  64798. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64799. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64800. */
  64801. var Analyser = /** @class */ (function () {
  64802. /**
  64803. * Creates a new analyser
  64804. * @param scene defines hosting scene
  64805. */
  64806. function Analyser(scene) {
  64807. /**
  64808. * Gets or sets the smoothing
  64809. * @ignorenaming
  64810. */
  64811. this.SMOOTHING = 0.75;
  64812. /**
  64813. * Gets or sets the FFT table size
  64814. * @ignorenaming
  64815. */
  64816. this.FFT_SIZE = 512;
  64817. /**
  64818. * Gets or sets the bar graph amplitude
  64819. * @ignorenaming
  64820. */
  64821. this.BARGRAPHAMPLITUDE = 256;
  64822. /**
  64823. * Gets or sets the position of the debug canvas
  64824. * @ignorenaming
  64825. */
  64826. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64827. /**
  64828. * Gets or sets the debug canvas size
  64829. * @ignorenaming
  64830. */
  64831. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64832. this._scene = scene;
  64833. this._audioEngine = BABYLON.Engine.audioEngine;
  64834. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64835. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64836. this._webAudioAnalyser.minDecibels = -140;
  64837. this._webAudioAnalyser.maxDecibels = 0;
  64838. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64839. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64840. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64841. }
  64842. }
  64843. /**
  64844. * Get the number of data values you will have to play with for the visualization
  64845. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64846. * @returns a number
  64847. */
  64848. Analyser.prototype.getFrequencyBinCount = function () {
  64849. if (this._audioEngine.canUseWebAudio) {
  64850. return this._webAudioAnalyser.frequencyBinCount;
  64851. }
  64852. else {
  64853. return 0;
  64854. }
  64855. };
  64856. /**
  64857. * Gets the current frequency data as a byte array
  64858. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64859. * @returns a Uint8Array
  64860. */
  64861. Analyser.prototype.getByteFrequencyData = function () {
  64862. if (this._audioEngine.canUseWebAudio) {
  64863. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64864. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64865. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64866. }
  64867. return this._byteFreqs;
  64868. };
  64869. /**
  64870. * Gets the current waveform as a byte array
  64871. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64872. * @returns a Uint8Array
  64873. */
  64874. Analyser.prototype.getByteTimeDomainData = function () {
  64875. if (this._audioEngine.canUseWebAudio) {
  64876. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64877. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64878. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64879. }
  64880. return this._byteTime;
  64881. };
  64882. /**
  64883. * Gets the current frequency data as a float array
  64884. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64885. * @returns a Float32Array
  64886. */
  64887. Analyser.prototype.getFloatFrequencyData = function () {
  64888. if (this._audioEngine.canUseWebAudio) {
  64889. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64890. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64891. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64892. }
  64893. return this._floatFreqs;
  64894. };
  64895. /**
  64896. * Renders the debug canvas
  64897. */
  64898. Analyser.prototype.drawDebugCanvas = function () {
  64899. var _this = this;
  64900. if (this._audioEngine.canUseWebAudio) {
  64901. if (!this._debugCanvas) {
  64902. this._debugCanvas = document.createElement("canvas");
  64903. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64904. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64905. this._debugCanvas.style.position = "absolute";
  64906. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64907. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64908. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64909. document.body.appendChild(this._debugCanvas);
  64910. this._registerFunc = function () {
  64911. _this.drawDebugCanvas();
  64912. };
  64913. this._scene.registerBeforeRender(this._registerFunc);
  64914. }
  64915. if (this._registerFunc && this._debugCanvasContext) {
  64916. var workingArray = this.getByteFrequencyData();
  64917. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64918. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64919. // Draw the frequency domain chart.
  64920. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64921. var value = workingArray[i];
  64922. var percent = value / this.BARGRAPHAMPLITUDE;
  64923. var height = this.DEBUGCANVASSIZE.height * percent;
  64924. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64925. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64926. var hue = i / this.getFrequencyBinCount() * 360;
  64927. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64928. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64929. }
  64930. }
  64931. }
  64932. };
  64933. /**
  64934. * Stops rendering the debug canvas and removes it
  64935. */
  64936. Analyser.prototype.stopDebugCanvas = function () {
  64937. if (this._debugCanvas) {
  64938. if (this._registerFunc) {
  64939. this._scene.unregisterBeforeRender(this._registerFunc);
  64940. this._registerFunc = null;
  64941. }
  64942. document.body.removeChild(this._debugCanvas);
  64943. this._debugCanvas = null;
  64944. this._debugCanvasContext = null;
  64945. }
  64946. };
  64947. /**
  64948. * Connects two audio nodes
  64949. * @param inputAudioNode defines first node to connect
  64950. * @param outputAudioNode defines second node to connect
  64951. */
  64952. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  64953. if (this._audioEngine.canUseWebAudio) {
  64954. inputAudioNode.connect(this._webAudioAnalyser);
  64955. this._webAudioAnalyser.connect(outputAudioNode);
  64956. }
  64957. };
  64958. /**
  64959. * Releases all associated resources
  64960. */
  64961. Analyser.prototype.dispose = function () {
  64962. if (this._audioEngine.canUseWebAudio) {
  64963. this._webAudioAnalyser.disconnect();
  64964. }
  64965. };
  64966. return Analyser;
  64967. }());
  64968. BABYLON.Analyser = Analyser;
  64969. })(BABYLON || (BABYLON = {}));
  64970. //# sourceMappingURL=babylon.analyser.js.map
  64971. var BABYLON;
  64972. (function (BABYLON) {
  64973. /**
  64974. * Wraps one or more Sound objects and selects one with random weight for playback.
  64975. */
  64976. var WeightedSound = /** @class */ (function () {
  64977. /**
  64978. * Creates a new WeightedSound from the list of sounds given.
  64979. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  64980. * @param sounds Array of Sounds that will be selected from.
  64981. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  64982. */
  64983. function WeightedSound(loop, sounds, weights) {
  64984. var _this = this;
  64985. /** When true a Sound will be selected and played when the current playing Sound completes. */
  64986. this.loop = false;
  64987. this._coneInnerAngle = 360;
  64988. this._coneOuterAngle = 360;
  64989. this._volume = 1;
  64990. /** A Sound is currently playing. */
  64991. this.isPlaying = false;
  64992. /** A Sound is currently paused. */
  64993. this.isPaused = false;
  64994. this._sounds = [];
  64995. this._weights = [];
  64996. if (sounds.length !== weights.length) {
  64997. throw new Error('Sounds length does not equal weights length');
  64998. }
  64999. this.loop = loop;
  65000. this._weights = weights;
  65001. // Normalize the weights
  65002. var weightSum = 0;
  65003. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  65004. var weight = weights_1[_i];
  65005. weightSum += weight;
  65006. }
  65007. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  65008. for (var i = 0; i < this._weights.length; i++) {
  65009. this._weights[i] *= invWeightSum;
  65010. }
  65011. this._sounds = sounds;
  65012. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  65013. var sound = _b[_a];
  65014. sound.onEndedObservable.add(function () { _this._onended(); });
  65015. }
  65016. }
  65017. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  65018. /**
  65019. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  65020. */
  65021. get: function () {
  65022. return this._coneInnerAngle;
  65023. },
  65024. /**
  65025. * The size of cone in degress for a directional sound in which there will be no attenuation.
  65026. */
  65027. set: function (value) {
  65028. if (value !== this._coneInnerAngle) {
  65029. if (this._coneOuterAngle < value) {
  65030. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65031. return;
  65032. }
  65033. this._coneInnerAngle = value;
  65034. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65035. var sound = _a[_i];
  65036. sound.directionalConeInnerAngle = value;
  65037. }
  65038. }
  65039. },
  65040. enumerable: true,
  65041. configurable: true
  65042. });
  65043. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  65044. /**
  65045. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65046. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65047. */
  65048. get: function () {
  65049. return this._coneOuterAngle;
  65050. },
  65051. /**
  65052. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65053. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65054. */
  65055. set: function (value) {
  65056. if (value !== this._coneOuterAngle) {
  65057. if (value < this._coneInnerAngle) {
  65058. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65059. return;
  65060. }
  65061. this._coneOuterAngle = value;
  65062. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65063. var sound = _a[_i];
  65064. sound.directionalConeOuterAngle = value;
  65065. }
  65066. }
  65067. },
  65068. enumerable: true,
  65069. configurable: true
  65070. });
  65071. Object.defineProperty(WeightedSound.prototype, "volume", {
  65072. /**
  65073. * Playback volume.
  65074. */
  65075. get: function () {
  65076. return this._volume;
  65077. },
  65078. /**
  65079. * Playback volume.
  65080. */
  65081. set: function (value) {
  65082. if (value !== this._volume) {
  65083. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65084. var sound = _a[_i];
  65085. sound.setVolume(value);
  65086. }
  65087. }
  65088. },
  65089. enumerable: true,
  65090. configurable: true
  65091. });
  65092. WeightedSound.prototype._onended = function () {
  65093. if (this._currentIndex !== undefined) {
  65094. this._sounds[this._currentIndex].autoplay = false;
  65095. }
  65096. if (this.loop && this.isPlaying) {
  65097. this.play();
  65098. }
  65099. else {
  65100. this.isPlaying = false;
  65101. }
  65102. };
  65103. /**
  65104. * Suspend playback
  65105. */
  65106. WeightedSound.prototype.pause = function () {
  65107. this.isPaused = true;
  65108. if (this._currentIndex !== undefined) {
  65109. this._sounds[this._currentIndex].pause();
  65110. }
  65111. };
  65112. /**
  65113. * Stop playback
  65114. */
  65115. WeightedSound.prototype.stop = function () {
  65116. this.isPlaying = false;
  65117. if (this._currentIndex !== undefined) {
  65118. this._sounds[this._currentIndex].stop();
  65119. }
  65120. };
  65121. /**
  65122. * Start playback.
  65123. * @param startOffset Position the clip head at a specific time in seconds.
  65124. */
  65125. WeightedSound.prototype.play = function (startOffset) {
  65126. if (!this.isPaused) {
  65127. this.stop();
  65128. var randomValue = Math.random();
  65129. var total = 0;
  65130. for (var i = 0; i < this._weights.length; i++) {
  65131. total += this._weights[i];
  65132. if (randomValue <= total) {
  65133. this._currentIndex = i;
  65134. break;
  65135. }
  65136. }
  65137. }
  65138. var sound = this._sounds[this._currentIndex];
  65139. if (sound.isReady()) {
  65140. sound.play(0, this.isPaused ? undefined : startOffset);
  65141. }
  65142. else {
  65143. sound.autoplay = true;
  65144. }
  65145. this.isPlaying = true;
  65146. this.isPaused = false;
  65147. };
  65148. return WeightedSound;
  65149. }());
  65150. BABYLON.WeightedSound = WeightedSound;
  65151. })(BABYLON || (BABYLON = {}));
  65152. //# sourceMappingURL=babylon.weightedsound.js.map
  65153. var BABYLON;
  65154. (function (BABYLON) {
  65155. var CubeTexture = /** @class */ (function (_super) {
  65156. __extends(CubeTexture, _super);
  65157. /**
  65158. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  65159. * as prefiltered data.
  65160. * @param rootUrl defines the url of the texture or the root name of the six images
  65161. * @param scene defines the scene the texture is attached to
  65162. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  65163. * @param noMipmap defines if mipmaps should be created or not
  65164. * @param files defines the six files to load for the different faces
  65165. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  65166. * @param onError defines a callback triggered in case of error during load
  65167. * @param format defines the internal format to use for the texture once loaded
  65168. * @param prefiltered defines whether or not the texture is created from prefiltered data
  65169. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  65170. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65171. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65172. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65173. * @return the cube texture
  65174. */
  65175. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  65176. if (extensions === void 0) { extensions = null; }
  65177. if (noMipmap === void 0) { noMipmap = false; }
  65178. if (files === void 0) { files = null; }
  65179. if (onLoad === void 0) { onLoad = null; }
  65180. if (onError === void 0) { onError = null; }
  65181. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65182. if (prefiltered === void 0) { prefiltered = false; }
  65183. if (forcedExtension === void 0) { forcedExtension = null; }
  65184. if (createPolynomials === void 0) { createPolynomials = false; }
  65185. if (lodScale === void 0) { lodScale = 0.8; }
  65186. if (lodOffset === void 0) { lodOffset = 0; }
  65187. var _this = _super.call(this, scene) || this;
  65188. /**
  65189. * Gets or sets the center of the bounding box associated with the cube texture
  65190. * It must define where the camera used to render the texture was set
  65191. */
  65192. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65193. _this._rotationY = 0;
  65194. /** @hidden */
  65195. _this._prefiltered = false;
  65196. _this.name = rootUrl;
  65197. _this.url = rootUrl;
  65198. _this._noMipmap = noMipmap;
  65199. _this.hasAlpha = false;
  65200. _this._format = format;
  65201. _this.isCube = true;
  65202. _this._textureMatrix = BABYLON.Matrix.Identity();
  65203. _this._createPolynomials = createPolynomials;
  65204. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65205. if (!rootUrl && !files) {
  65206. return _this;
  65207. }
  65208. var lastDot = rootUrl.lastIndexOf(".");
  65209. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  65210. var isDDS = (extension === ".dds");
  65211. var isEnv = (extension === ".env");
  65212. if (isEnv) {
  65213. _this.gammaSpace = false;
  65214. _this._prefiltered = false;
  65215. }
  65216. else {
  65217. _this._prefiltered = prefiltered;
  65218. if (prefiltered) {
  65219. _this.gammaSpace = false;
  65220. }
  65221. }
  65222. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  65223. if (!files) {
  65224. if (!isEnv && !isDDS && !extensions) {
  65225. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  65226. }
  65227. files = [];
  65228. if (extensions) {
  65229. for (var index = 0; index < extensions.length; index++) {
  65230. files.push(rootUrl + extensions[index]);
  65231. }
  65232. }
  65233. }
  65234. _this._files = files;
  65235. if (!_this._texture) {
  65236. if (!scene.useDelayedTextureLoading) {
  65237. if (prefiltered) {
  65238. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  65239. }
  65240. else {
  65241. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  65242. }
  65243. }
  65244. else {
  65245. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65246. }
  65247. }
  65248. else if (onLoad) {
  65249. if (_this._texture.isReady) {
  65250. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  65251. }
  65252. else {
  65253. _this._texture.onLoadedObservable.add(onLoad);
  65254. }
  65255. }
  65256. return _this;
  65257. }
  65258. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  65259. get: function () {
  65260. return this._boundingBoxSize;
  65261. },
  65262. /**
  65263. * Gets or sets the size of the bounding box associated with the cube texture
  65264. * When defined, the cubemap will switch to local mode
  65265. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65266. * @example https://www.babylonjs-playground.com/#RNASML
  65267. */
  65268. set: function (value) {
  65269. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65270. return;
  65271. }
  65272. this._boundingBoxSize = value;
  65273. var scene = this.getScene();
  65274. if (scene) {
  65275. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65276. }
  65277. },
  65278. enumerable: true,
  65279. configurable: true
  65280. });
  65281. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  65282. /**
  65283. * Gets texture matrix rotation angle around Y axis radians.
  65284. */
  65285. get: function () {
  65286. return this._rotationY;
  65287. },
  65288. /**
  65289. * Sets texture matrix rotation angle around Y axis in radians.
  65290. */
  65291. set: function (value) {
  65292. this._rotationY = value;
  65293. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  65294. },
  65295. enumerable: true,
  65296. configurable: true
  65297. });
  65298. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  65299. var rootUrlKey = "";
  65300. files.forEach(function (url) { return rootUrlKey += url; });
  65301. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  65302. };
  65303. /**
  65304. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  65305. * @param url defines the url of the prefiltered texture
  65306. * @param scene defines the scene the texture is attached to
  65307. * @param forcedExtension defines the extension of the file if different from the url
  65308. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65309. * @return the prefiltered texture
  65310. */
  65311. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  65312. if (forcedExtension === void 0) { forcedExtension = null; }
  65313. if (createPolynomials === void 0) { createPolynomials = true; }
  65314. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  65315. };
  65316. // Methods
  65317. CubeTexture.prototype.delayLoad = function () {
  65318. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65319. return;
  65320. }
  65321. var scene = this.getScene();
  65322. if (!scene) {
  65323. return;
  65324. }
  65325. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65326. this._texture = this._getFromCache(this.url, this._noMipmap);
  65327. if (!this._texture) {
  65328. if (this._prefiltered) {
  65329. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  65330. }
  65331. else {
  65332. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  65333. }
  65334. }
  65335. };
  65336. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  65337. return this._textureMatrix;
  65338. };
  65339. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  65340. this._textureMatrix = value;
  65341. };
  65342. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65343. var texture = BABYLON.SerializationHelper.Parse(function () {
  65344. var prefiltered = false;
  65345. if (parsedTexture.prefiltered) {
  65346. prefiltered = parsedTexture.prefiltered;
  65347. }
  65348. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  65349. }, parsedTexture, scene);
  65350. // Local Cubemaps
  65351. if (parsedTexture.boundingBoxPosition) {
  65352. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  65353. }
  65354. if (parsedTexture.boundingBoxSize) {
  65355. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  65356. }
  65357. // Animations
  65358. if (parsedTexture.animations) {
  65359. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  65360. var parsedAnimation = parsedTexture.animations[animationIndex];
  65361. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  65362. }
  65363. }
  65364. return texture;
  65365. };
  65366. CubeTexture.prototype.clone = function () {
  65367. var _this = this;
  65368. return BABYLON.SerializationHelper.Clone(function () {
  65369. var scene = _this.getScene();
  65370. if (!scene) {
  65371. return _this;
  65372. }
  65373. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  65374. }, this);
  65375. };
  65376. __decorate([
  65377. BABYLON.serialize("rotationY")
  65378. ], CubeTexture.prototype, "_rotationY", void 0);
  65379. return CubeTexture;
  65380. }(BABYLON.BaseTexture));
  65381. BABYLON.CubeTexture = CubeTexture;
  65382. })(BABYLON || (BABYLON = {}));
  65383. //# sourceMappingURL=babylon.cubeTexture.js.map
  65384. var BABYLON;
  65385. (function (BABYLON) {
  65386. /**
  65387. * Raw cube texture where the raw buffers are passed in
  65388. */
  65389. var RawCubeTexture = /** @class */ (function (_super) {
  65390. __extends(RawCubeTexture, _super);
  65391. /**
  65392. * Creates a cube texture where the raw buffers are passed in.
  65393. * @param scene defines the scene the texture is attached to
  65394. * @param data defines the array of data to use to create each face
  65395. * @param size defines the size of the textures
  65396. * @param format defines the format of the data
  65397. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  65398. * @param generateMipMaps defines if the engine should generate the mip levels
  65399. * @param invertY defines if data must be stored with Y axis inverted
  65400. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  65401. * @param compression defines the compression used (null by default)
  65402. */
  65403. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  65404. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65405. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65406. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65407. if (invertY === void 0) { invertY = false; }
  65408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65409. if (compression === void 0) { compression = null; }
  65410. var _this = _super.call(this, "", scene) || this;
  65411. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  65412. return _this;
  65413. }
  65414. /**
  65415. * Updates the raw cube texture.
  65416. * @param data defines the data to store
  65417. * @param format defines the data format
  65418. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  65419. * @param invertY defines if data must be stored with Y axis inverted
  65420. * @param compression defines the compression used (null by default)
  65421. * @param level defines which level of the texture to update
  65422. */
  65423. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  65424. if (compression === void 0) { compression = null; }
  65425. if (level === void 0) { level = 0; }
  65426. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  65427. };
  65428. /**
  65429. * Updates a raw cube texture with RGBD encoded data.
  65430. * @param data defines the array of data [mipmap][face] to use to create each face
  65431. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  65432. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65433. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65434. * @returns a promsie that resolves when the operation is complete
  65435. */
  65436. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  65437. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  65438. if (lodScale === void 0) { lodScale = 0.8; }
  65439. if (lodOffset === void 0) { lodOffset = 0; }
  65440. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  65441. };
  65442. /**
  65443. * Clones the raw cube texture.
  65444. * @return a new cube texture
  65445. */
  65446. RawCubeTexture.prototype.clone = function () {
  65447. var _this = this;
  65448. return BABYLON.SerializationHelper.Clone(function () {
  65449. var scene = _this.getScene();
  65450. var internalTexture = _this._texture;
  65451. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  65452. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  65453. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  65454. }
  65455. return texture;
  65456. }, this);
  65457. };
  65458. /** @hidden */
  65459. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  65460. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  65461. internalTexture._bufferViewArrayArray = data;
  65462. internalTexture._lodGenerationScale = lodScale;
  65463. internalTexture._lodGenerationOffset = lodOffset;
  65464. internalTexture._sphericalPolynomial = sphericalPolynomial;
  65465. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  65466. internalTexture.isReady = true;
  65467. });
  65468. };
  65469. return RawCubeTexture;
  65470. }(BABYLON.CubeTexture));
  65471. BABYLON.RawCubeTexture = RawCubeTexture;
  65472. })(BABYLON || (BABYLON = {}));
  65473. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  65474. var BABYLON;
  65475. (function (BABYLON) {
  65476. var RenderTargetTexture = /** @class */ (function (_super) {
  65477. __extends(RenderTargetTexture, _super);
  65478. /**
  65479. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  65480. * or used a shadow, depth texture...
  65481. * @param name The friendly name of the texture
  65482. * @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)
  65483. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  65484. * @param generateMipMaps True if mip maps need to be generated after render.
  65485. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  65486. * @param type The type of the buffer in the RTT (int, half float, float...)
  65487. * @param isCube True if a cube texture needs to be created
  65488. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  65489. * @param generateDepthBuffer True to generate a depth buffer
  65490. * @param generateStencilBuffer True to generate a stencil buffer
  65491. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  65492. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  65493. */
  65494. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  65495. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  65496. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65497. if (isCube === void 0) { isCube = false; }
  65498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65499. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65500. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  65501. if (isMulti === void 0) { isMulti = false; }
  65502. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65503. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65504. _this.isCube = isCube;
  65505. _this.renderParticles = true;
  65506. _this.renderSprites = false;
  65507. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  65508. _this.ignoreCameraViewport = false;
  65509. // Events
  65510. /**
  65511. * An event triggered when the texture is unbind.
  65512. */
  65513. _this.onBeforeBindObservable = new BABYLON.Observable();
  65514. /**
  65515. * An event triggered when the texture is unbind.
  65516. */
  65517. _this.onAfterUnbindObservable = new BABYLON.Observable();
  65518. /**
  65519. * An event triggered before rendering the texture
  65520. */
  65521. _this.onBeforeRenderObservable = new BABYLON.Observable();
  65522. /**
  65523. * An event triggered after rendering the texture
  65524. */
  65525. _this.onAfterRenderObservable = new BABYLON.Observable();
  65526. /**
  65527. * An event triggered after the texture clear
  65528. */
  65529. _this.onClearObservable = new BABYLON.Observable();
  65530. _this._currentRefreshId = -1;
  65531. _this._refreshRate = 1;
  65532. _this._samples = 1;
  65533. /**
  65534. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  65535. * It must define where the camera used to render the texture is set
  65536. */
  65537. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65538. scene = _this.getScene();
  65539. if (!scene) {
  65540. return _this;
  65541. }
  65542. _this.renderList = new Array();
  65543. _this._engine = scene.getEngine();
  65544. _this.name = name;
  65545. _this.isRenderTarget = true;
  65546. _this._initialSizeParameter = size;
  65547. _this._processSizeParameter(size);
  65548. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  65549. });
  65550. _this._generateMipMaps = generateMipMaps ? true : false;
  65551. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  65552. // Rendering groups
  65553. _this._renderingManager = new BABYLON.RenderingManager(scene);
  65554. _this._renderingManager._useSceneAutoClearSetup = true;
  65555. if (isMulti) {
  65556. return _this;
  65557. }
  65558. _this._renderTargetOptions = {
  65559. generateMipMaps: generateMipMaps,
  65560. type: type,
  65561. format: format,
  65562. samplingMode: samplingMode,
  65563. generateDepthBuffer: generateDepthBuffer,
  65564. generateStencilBuffer: generateStencilBuffer
  65565. };
  65566. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65567. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65568. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65569. }
  65570. if (isCube) {
  65571. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65572. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65573. _this._textureMatrix = BABYLON.Matrix.Identity();
  65574. }
  65575. else {
  65576. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65577. }
  65578. return _this;
  65579. }
  65580. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65581. get: function () {
  65582. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65583. },
  65584. enumerable: true,
  65585. configurable: true
  65586. });
  65587. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65588. get: function () {
  65589. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65590. },
  65591. enumerable: true,
  65592. configurable: true
  65593. });
  65594. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65595. get: function () {
  65596. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65597. },
  65598. enumerable: true,
  65599. configurable: true
  65600. });
  65601. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  65602. /**
  65603. * Use this list to define the list of mesh you want to render.
  65604. */
  65605. get: function () {
  65606. return this._renderList;
  65607. },
  65608. set: function (value) {
  65609. this._renderList = value;
  65610. if (this._renderList) {
  65611. this._hookArray(this._renderList);
  65612. }
  65613. },
  65614. enumerable: true,
  65615. configurable: true
  65616. });
  65617. RenderTargetTexture.prototype._hookArray = function (array) {
  65618. var _this = this;
  65619. var oldPush = array.push;
  65620. array.push = function () {
  65621. var items = [];
  65622. for (var _i = 0; _i < arguments.length; _i++) {
  65623. items[_i] = arguments[_i];
  65624. }
  65625. var result = oldPush.apply(array, items);
  65626. _this.getScene().meshes.forEach(function (mesh) {
  65627. mesh._markSubMeshesAsLightDirty();
  65628. });
  65629. return result;
  65630. };
  65631. var oldSplice = array.splice;
  65632. array.splice = function (index, deleteCount) {
  65633. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65634. _this.getScene().meshes.forEach(function (mesh) {
  65635. mesh._markSubMeshesAsLightDirty();
  65636. });
  65637. return deleted;
  65638. };
  65639. };
  65640. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  65641. set: function (callback) {
  65642. if (this._onAfterUnbindObserver) {
  65643. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  65644. }
  65645. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  65646. },
  65647. enumerable: true,
  65648. configurable: true
  65649. });
  65650. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  65651. set: function (callback) {
  65652. if (this._onBeforeRenderObserver) {
  65653. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65654. }
  65655. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65656. },
  65657. enumerable: true,
  65658. configurable: true
  65659. });
  65660. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  65661. set: function (callback) {
  65662. if (this._onAfterRenderObserver) {
  65663. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65664. }
  65665. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65666. },
  65667. enumerable: true,
  65668. configurable: true
  65669. });
  65670. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  65671. set: function (callback) {
  65672. if (this._onClearObserver) {
  65673. this.onClearObservable.remove(this._onClearObserver);
  65674. }
  65675. this._onClearObserver = this.onClearObservable.add(callback);
  65676. },
  65677. enumerable: true,
  65678. configurable: true
  65679. });
  65680. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  65681. get: function () {
  65682. return this._renderTargetOptions;
  65683. },
  65684. enumerable: true,
  65685. configurable: true
  65686. });
  65687. RenderTargetTexture.prototype._onRatioRescale = function () {
  65688. if (this._sizeRatio) {
  65689. this.resize(this._initialSizeParameter);
  65690. }
  65691. };
  65692. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  65693. get: function () {
  65694. return this._boundingBoxSize;
  65695. },
  65696. /**
  65697. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  65698. * When defined, the cubemap will switch to local mode
  65699. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65700. * @example https://www.babylonjs-playground.com/#RNASML
  65701. */
  65702. set: function (value) {
  65703. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65704. return;
  65705. }
  65706. this._boundingBoxSize = value;
  65707. var scene = this.getScene();
  65708. if (scene) {
  65709. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65710. }
  65711. },
  65712. enumerable: true,
  65713. configurable: true
  65714. });
  65715. /**
  65716. * Creates a depth stencil texture.
  65717. * This is only available in WebGL 2 or with the depth texture extension available.
  65718. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  65719. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  65720. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  65721. */
  65722. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  65723. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  65724. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  65725. if (generateStencil === void 0) { generateStencil = false; }
  65726. if (!this.getScene()) {
  65727. return;
  65728. }
  65729. var engine = this.getScene().getEngine();
  65730. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  65731. bilinearFiltering: bilinearFiltering,
  65732. comparisonFunction: comparisonFunction,
  65733. generateStencil: generateStencil,
  65734. isCube: this.isCube
  65735. });
  65736. engine.setFrameBufferDepthStencilTexture(this);
  65737. };
  65738. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  65739. if (size.ratio) {
  65740. this._sizeRatio = size.ratio;
  65741. this._size = {
  65742. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  65743. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  65744. };
  65745. }
  65746. else {
  65747. this._size = size;
  65748. }
  65749. };
  65750. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  65751. get: function () {
  65752. return this._samples;
  65753. },
  65754. set: function (value) {
  65755. if (this._samples === value) {
  65756. return;
  65757. }
  65758. var scene = this.getScene();
  65759. if (!scene) {
  65760. return;
  65761. }
  65762. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  65763. },
  65764. enumerable: true,
  65765. configurable: true
  65766. });
  65767. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  65768. this._currentRefreshId = -1;
  65769. };
  65770. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  65771. get: function () {
  65772. return this._refreshRate;
  65773. },
  65774. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65775. set: function (value) {
  65776. this._refreshRate = value;
  65777. this.resetRefreshCounter();
  65778. },
  65779. enumerable: true,
  65780. configurable: true
  65781. });
  65782. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  65783. if (!this._postProcessManager) {
  65784. var scene = this.getScene();
  65785. if (!scene) {
  65786. return;
  65787. }
  65788. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  65789. this._postProcesses = new Array();
  65790. }
  65791. this._postProcesses.push(postProcess);
  65792. this._postProcesses[0].autoClear = false;
  65793. };
  65794. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  65795. if (!this._postProcesses) {
  65796. return;
  65797. }
  65798. if (dispose) {
  65799. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  65800. var postProcess = _a[_i];
  65801. postProcess.dispose();
  65802. }
  65803. }
  65804. this._postProcesses = [];
  65805. };
  65806. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  65807. if (!this._postProcesses) {
  65808. return;
  65809. }
  65810. var index = this._postProcesses.indexOf(postProcess);
  65811. if (index === -1) {
  65812. return;
  65813. }
  65814. this._postProcesses.splice(index, 1);
  65815. if (this._postProcesses.length > 0) {
  65816. this._postProcesses[0].autoClear = false;
  65817. }
  65818. };
  65819. RenderTargetTexture.prototype._shouldRender = function () {
  65820. if (this._currentRefreshId === -1) { // At least render once
  65821. this._currentRefreshId = 1;
  65822. return true;
  65823. }
  65824. if (this.refreshRate === this._currentRefreshId) {
  65825. this._currentRefreshId = 1;
  65826. return true;
  65827. }
  65828. this._currentRefreshId++;
  65829. return false;
  65830. };
  65831. RenderTargetTexture.prototype.getRenderSize = function () {
  65832. if (this._size.width) {
  65833. return this._size.width;
  65834. }
  65835. return this._size;
  65836. };
  65837. RenderTargetTexture.prototype.getRenderWidth = function () {
  65838. if (this._size.width) {
  65839. return this._size.width;
  65840. }
  65841. return this._size;
  65842. };
  65843. RenderTargetTexture.prototype.getRenderHeight = function () {
  65844. if (this._size.width) {
  65845. return this._size.height;
  65846. }
  65847. return this._size;
  65848. };
  65849. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  65850. get: function () {
  65851. return true;
  65852. },
  65853. enumerable: true,
  65854. configurable: true
  65855. });
  65856. RenderTargetTexture.prototype.scale = function (ratio) {
  65857. var newSize = this.getRenderSize() * ratio;
  65858. this.resize(newSize);
  65859. };
  65860. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  65861. if (this.isCube) {
  65862. return this._textureMatrix;
  65863. }
  65864. return _super.prototype.getReflectionTextureMatrix.call(this);
  65865. };
  65866. RenderTargetTexture.prototype.resize = function (size) {
  65867. this.releaseInternalTexture();
  65868. var scene = this.getScene();
  65869. if (!scene) {
  65870. return;
  65871. }
  65872. this._processSizeParameter(size);
  65873. if (this.isCube) {
  65874. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  65875. }
  65876. else {
  65877. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  65878. }
  65879. };
  65880. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  65881. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  65882. if (dumpForDebug === void 0) { dumpForDebug = false; }
  65883. var scene = this.getScene();
  65884. if (!scene) {
  65885. return;
  65886. }
  65887. var engine = scene.getEngine();
  65888. if (this.useCameraPostProcesses !== undefined) {
  65889. useCameraPostProcess = this.useCameraPostProcesses;
  65890. }
  65891. if (this._waitingRenderList) {
  65892. this.renderList = [];
  65893. for (var index = 0; index < this._waitingRenderList.length; index++) {
  65894. var id = this._waitingRenderList[index];
  65895. var mesh_1 = scene.getMeshByID(id);
  65896. if (mesh_1) {
  65897. this.renderList.push(mesh_1);
  65898. }
  65899. }
  65900. delete this._waitingRenderList;
  65901. }
  65902. // Is predicate defined?
  65903. if (this.renderListPredicate) {
  65904. if (this.renderList) {
  65905. this.renderList.splice(0); // Clear previous renderList
  65906. }
  65907. else {
  65908. this.renderList = [];
  65909. }
  65910. var scene = this.getScene();
  65911. if (!scene) {
  65912. return;
  65913. }
  65914. var sceneMeshes = scene.meshes;
  65915. for (var index = 0; index < sceneMeshes.length; index++) {
  65916. var mesh = sceneMeshes[index];
  65917. if (this.renderListPredicate(mesh)) {
  65918. this.renderList.push(mesh);
  65919. }
  65920. }
  65921. }
  65922. this.onBeforeBindObservable.notifyObservers(this);
  65923. // Set custom projection.
  65924. // Needs to be before binding to prevent changing the aspect ratio.
  65925. var camera;
  65926. if (this.activeCamera) {
  65927. camera = this.activeCamera;
  65928. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65929. if (this.activeCamera !== scene.activeCamera) {
  65930. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  65931. }
  65932. }
  65933. else {
  65934. camera = scene.activeCamera;
  65935. if (camera) {
  65936. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65937. }
  65938. }
  65939. // Prepare renderingManager
  65940. this._renderingManager.reset();
  65941. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  65942. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  65943. var sceneRenderId = scene.getRenderId();
  65944. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  65945. var mesh = currentRenderList[meshIndex];
  65946. if (mesh) {
  65947. if (!mesh.isReady(this.refreshRate === 0)) {
  65948. this.resetRefreshCounter();
  65949. continue;
  65950. }
  65951. mesh._preActivateForIntermediateRendering(sceneRenderId);
  65952. var isMasked = void 0;
  65953. if (!this.renderList && camera) {
  65954. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  65955. }
  65956. else {
  65957. isMasked = false;
  65958. }
  65959. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  65960. mesh._activate(sceneRenderId);
  65961. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  65962. var subMesh = mesh.subMeshes[subIndex];
  65963. scene._activeIndices.addCount(subMesh.indexCount, false);
  65964. this._renderingManager.dispatch(subMesh, mesh);
  65965. }
  65966. }
  65967. }
  65968. }
  65969. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  65970. var particleSystem = scene.particleSystems[particleIndex];
  65971. var emitter = particleSystem.emitter;
  65972. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  65973. continue;
  65974. }
  65975. if (currentRenderList.indexOf(emitter) >= 0) {
  65976. this._renderingManager.dispatchParticles(particleSystem);
  65977. }
  65978. }
  65979. if (this.isCube) {
  65980. for (var face = 0; face < 6; face++) {
  65981. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65982. scene.incrementRenderId();
  65983. scene.resetCachedMaterial();
  65984. }
  65985. }
  65986. else {
  65987. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65988. }
  65989. this.onAfterUnbindObservable.notifyObservers(this);
  65990. if (scene.activeCamera) {
  65991. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  65992. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  65993. }
  65994. engine.setViewport(scene.activeCamera.viewport);
  65995. }
  65996. scene.resetCachedMaterial();
  65997. };
  65998. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65999. var minimum = 128;
  66000. var x = renderDimension * scale;
  66001. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  66002. // Ensure we don't exceed the render dimension (while staying POT)
  66003. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  66004. };
  66005. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66006. var _this = this;
  66007. if (!this._texture) {
  66008. return;
  66009. }
  66010. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  66011. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66012. });
  66013. };
  66014. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  66015. var scene = this.getScene();
  66016. if (!scene) {
  66017. return;
  66018. }
  66019. var engine = scene.getEngine();
  66020. if (!this._texture) {
  66021. return;
  66022. }
  66023. // Bind
  66024. if (this._postProcessManager) {
  66025. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  66026. }
  66027. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  66028. if (this._texture) {
  66029. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  66030. }
  66031. }
  66032. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  66033. // Clear
  66034. if (this.onClearObservable.hasObservers()) {
  66035. this.onClearObservable.notifyObservers(engine);
  66036. }
  66037. else {
  66038. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  66039. }
  66040. if (!this._doNotChangeAspectRatio) {
  66041. scene.updateTransformMatrix(true);
  66042. }
  66043. // Render
  66044. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  66045. if (this._postProcessManager) {
  66046. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  66047. }
  66048. else if (useCameraPostProcess) {
  66049. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  66050. }
  66051. if (!this._doNotChangeAspectRatio) {
  66052. scene.updateTransformMatrix(true);
  66053. }
  66054. // Dump ?
  66055. if (dumpForDebug) {
  66056. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  66057. }
  66058. // Unbind
  66059. if (!this.isCube || faceIndex === 5) {
  66060. if (this.isCube) {
  66061. if (faceIndex === 5) {
  66062. engine.generateMipMapsForCubemap(this._texture);
  66063. }
  66064. }
  66065. this.unbindFrameBuffer(engine, faceIndex);
  66066. }
  66067. else {
  66068. this.onAfterRenderObservable.notifyObservers(faceIndex);
  66069. }
  66070. };
  66071. /**
  66072. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  66073. * This allowed control for front to back rendering or reversly depending of the special needs.
  66074. *
  66075. * @param renderingGroupId The rendering group id corresponding to its index
  66076. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  66077. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  66078. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  66079. */
  66080. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  66081. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  66082. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  66083. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  66084. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  66085. };
  66086. /**
  66087. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  66088. *
  66089. * @param renderingGroupId The rendering group id corresponding to its index
  66090. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  66091. */
  66092. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  66093. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  66094. this._renderingManager._useSceneAutoClearSetup = false;
  66095. };
  66096. RenderTargetTexture.prototype.clone = function () {
  66097. var textureSize = this.getSize();
  66098. 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);
  66099. // Base texture
  66100. newTexture.hasAlpha = this.hasAlpha;
  66101. newTexture.level = this.level;
  66102. // RenderTarget Texture
  66103. newTexture.coordinatesMode = this.coordinatesMode;
  66104. if (this.renderList) {
  66105. newTexture.renderList = this.renderList.slice(0);
  66106. }
  66107. return newTexture;
  66108. };
  66109. RenderTargetTexture.prototype.serialize = function () {
  66110. if (!this.name) {
  66111. return null;
  66112. }
  66113. var serializationObject = _super.prototype.serialize.call(this);
  66114. serializationObject.renderTargetSize = this.getRenderSize();
  66115. serializationObject.renderList = [];
  66116. if (this.renderList) {
  66117. for (var index = 0; index < this.renderList.length; index++) {
  66118. serializationObject.renderList.push(this.renderList[index].id);
  66119. }
  66120. }
  66121. return serializationObject;
  66122. };
  66123. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  66124. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  66125. var objBuffer = this.getInternalTexture();
  66126. var scene = this.getScene();
  66127. if (objBuffer && scene) {
  66128. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  66129. }
  66130. };
  66131. RenderTargetTexture.prototype.dispose = function () {
  66132. if (this._postProcessManager) {
  66133. this._postProcessManager.dispose();
  66134. this._postProcessManager = null;
  66135. }
  66136. this.clearPostProcesses(true);
  66137. if (this._resizeObserver) {
  66138. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  66139. this._resizeObserver = null;
  66140. }
  66141. this.renderList = null;
  66142. // Remove from custom render targets
  66143. var scene = this.getScene();
  66144. if (!scene) {
  66145. return;
  66146. }
  66147. var index = scene.customRenderTargets.indexOf(this);
  66148. if (index >= 0) {
  66149. scene.customRenderTargets.splice(index, 1);
  66150. }
  66151. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  66152. var camera = _a[_i];
  66153. index = camera.customRenderTargets.indexOf(this);
  66154. if (index >= 0) {
  66155. camera.customRenderTargets.splice(index, 1);
  66156. }
  66157. }
  66158. _super.prototype.dispose.call(this);
  66159. };
  66160. RenderTargetTexture.prototype._rebuild = function () {
  66161. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  66162. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  66163. }
  66164. if (this._postProcessManager) {
  66165. this._postProcessManager._rebuild();
  66166. }
  66167. };
  66168. /**
  66169. * Clear the info related to rendering groups preventing retention point in material dispose.
  66170. */
  66171. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  66172. if (this._renderingManager) {
  66173. this._renderingManager.freeRenderingGroups();
  66174. }
  66175. };
  66176. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  66177. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  66178. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  66179. return RenderTargetTexture;
  66180. }(BABYLON.Texture));
  66181. BABYLON.RenderTargetTexture = RenderTargetTexture;
  66182. })(BABYLON || (BABYLON = {}));
  66183. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  66184. var BABYLON;
  66185. (function (BABYLON) {
  66186. ;
  66187. var MultiRenderTarget = /** @class */ (function (_super) {
  66188. __extends(MultiRenderTarget, _super);
  66189. function MultiRenderTarget(name, size, count, scene, options) {
  66190. var _this = this;
  66191. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  66192. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  66193. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  66194. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  66195. _this._engine = scene.getEngine();
  66196. if (!_this.isSupported) {
  66197. _this.dispose();
  66198. return;
  66199. }
  66200. var types = [];
  66201. var samplingModes = [];
  66202. for (var i = 0; i < count; i++) {
  66203. if (options && options.types && options.types[i] !== undefined) {
  66204. types.push(options.types[i]);
  66205. }
  66206. else {
  66207. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66208. }
  66209. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  66210. samplingModes.push(options.samplingModes[i]);
  66211. }
  66212. else {
  66213. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66214. }
  66215. }
  66216. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  66217. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  66218. _this._size = size;
  66219. _this._multiRenderTargetOptions = {
  66220. samplingModes: samplingModes,
  66221. generateMipMaps: generateMipMaps,
  66222. generateDepthBuffer: generateDepthBuffer,
  66223. generateStencilBuffer: generateStencilBuffer,
  66224. generateDepthTexture: generateDepthTexture,
  66225. types: types,
  66226. textureCount: count
  66227. };
  66228. _this._createInternalTextures();
  66229. _this._createTextures();
  66230. return _this;
  66231. }
  66232. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  66233. get: function () {
  66234. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  66235. },
  66236. enumerable: true,
  66237. configurable: true
  66238. });
  66239. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  66240. get: function () {
  66241. return this._textures;
  66242. },
  66243. enumerable: true,
  66244. configurable: true
  66245. });
  66246. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  66247. get: function () {
  66248. return this._textures[this._textures.length - 1];
  66249. },
  66250. enumerable: true,
  66251. configurable: true
  66252. });
  66253. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  66254. set: function (wrap) {
  66255. if (this._textures) {
  66256. for (var i = 0; i < this._textures.length; i++) {
  66257. this._textures[i].wrapU = wrap;
  66258. }
  66259. }
  66260. },
  66261. enumerable: true,
  66262. configurable: true
  66263. });
  66264. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  66265. set: function (wrap) {
  66266. if (this._textures) {
  66267. for (var i = 0; i < this._textures.length; i++) {
  66268. this._textures[i].wrapV = wrap;
  66269. }
  66270. }
  66271. },
  66272. enumerable: true,
  66273. configurable: true
  66274. });
  66275. MultiRenderTarget.prototype._rebuild = function () {
  66276. this.releaseInternalTextures();
  66277. this._createInternalTextures();
  66278. for (var i = 0; i < this._internalTextures.length; i++) {
  66279. var texture = this._textures[i];
  66280. texture._texture = this._internalTextures[i];
  66281. }
  66282. // Keeps references to frame buffer and stencil/depth buffer
  66283. this._texture = this._internalTextures[0];
  66284. };
  66285. MultiRenderTarget.prototype._createInternalTextures = function () {
  66286. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  66287. };
  66288. MultiRenderTarget.prototype._createTextures = function () {
  66289. this._textures = [];
  66290. for (var i = 0; i < this._internalTextures.length; i++) {
  66291. var texture = new BABYLON.Texture(null, this.getScene());
  66292. texture._texture = this._internalTextures[i];
  66293. this._textures.push(texture);
  66294. }
  66295. // Keeps references to frame buffer and stencil/depth buffer
  66296. this._texture = this._internalTextures[0];
  66297. };
  66298. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  66299. get: function () {
  66300. return this._samples;
  66301. },
  66302. set: function (value) {
  66303. if (this._samples === value) {
  66304. return;
  66305. }
  66306. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  66307. },
  66308. enumerable: true,
  66309. configurable: true
  66310. });
  66311. MultiRenderTarget.prototype.resize = function (size) {
  66312. this.releaseInternalTextures();
  66313. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  66314. this._createInternalTextures();
  66315. };
  66316. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66317. var _this = this;
  66318. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  66319. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66320. });
  66321. };
  66322. MultiRenderTarget.prototype.dispose = function () {
  66323. this.releaseInternalTextures();
  66324. _super.prototype.dispose.call(this);
  66325. };
  66326. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  66327. if (!this._internalTextures) {
  66328. return;
  66329. }
  66330. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  66331. if (this._internalTextures[i] !== undefined) {
  66332. this._internalTextures[i].dispose();
  66333. this._internalTextures.splice(i, 1);
  66334. }
  66335. }
  66336. };
  66337. return MultiRenderTarget;
  66338. }(BABYLON.RenderTargetTexture));
  66339. BABYLON.MultiRenderTarget = MultiRenderTarget;
  66340. })(BABYLON || (BABYLON = {}));
  66341. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  66342. var BABYLON;
  66343. (function (BABYLON) {
  66344. var MirrorTexture = /** @class */ (function (_super) {
  66345. __extends(MirrorTexture, _super);
  66346. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  66347. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66349. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66350. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  66351. _this.scene = scene;
  66352. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  66353. _this._transformMatrix = BABYLON.Matrix.Zero();
  66354. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  66355. _this._adaptiveBlurKernel = 0;
  66356. _this._blurKernelX = 0;
  66357. _this._blurKernelY = 0;
  66358. _this._blurRatio = 1.0;
  66359. _this.ignoreCameraViewport = true;
  66360. _this._updateGammaSpace();
  66361. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  66362. _this._updateGammaSpace;
  66363. });
  66364. _this.onBeforeRenderObservable.add(function () {
  66365. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  66366. _this._savedViewMatrix = scene.getViewMatrix();
  66367. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  66368. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  66369. scene.clipPlane = _this.mirrorPlane;
  66370. scene.getEngine().cullBackFaces = false;
  66371. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  66372. });
  66373. _this.onAfterRenderObservable.add(function () {
  66374. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  66375. scene.getEngine().cullBackFaces = true;
  66376. scene._mirroredCameraPosition = null;
  66377. delete scene.clipPlane;
  66378. });
  66379. return _this;
  66380. }
  66381. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  66382. get: function () {
  66383. return this._blurRatio;
  66384. },
  66385. set: function (value) {
  66386. if (this._blurRatio === value) {
  66387. return;
  66388. }
  66389. this._blurRatio = value;
  66390. this._preparePostProcesses();
  66391. },
  66392. enumerable: true,
  66393. configurable: true
  66394. });
  66395. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  66396. set: function (value) {
  66397. this._adaptiveBlurKernel = value;
  66398. this._autoComputeBlurKernel();
  66399. },
  66400. enumerable: true,
  66401. configurable: true
  66402. });
  66403. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  66404. set: function (value) {
  66405. this.blurKernelX = value;
  66406. this.blurKernelY = value;
  66407. },
  66408. enumerable: true,
  66409. configurable: true
  66410. });
  66411. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  66412. get: function () {
  66413. return this._blurKernelX;
  66414. },
  66415. set: function (value) {
  66416. if (this._blurKernelX === value) {
  66417. return;
  66418. }
  66419. this._blurKernelX = value;
  66420. this._preparePostProcesses();
  66421. },
  66422. enumerable: true,
  66423. configurable: true
  66424. });
  66425. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  66426. get: function () {
  66427. return this._blurKernelY;
  66428. },
  66429. set: function (value) {
  66430. if (this._blurKernelY === value) {
  66431. return;
  66432. }
  66433. this._blurKernelY = value;
  66434. this._preparePostProcesses();
  66435. },
  66436. enumerable: true,
  66437. configurable: true
  66438. });
  66439. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  66440. var engine = this.getScene().getEngine();
  66441. var dw = this.getRenderWidth() / engine.getRenderWidth();
  66442. var dh = this.getRenderHeight() / engine.getRenderHeight();
  66443. this.blurKernelX = this._adaptiveBlurKernel * dw;
  66444. this.blurKernelY = this._adaptiveBlurKernel * dh;
  66445. };
  66446. MirrorTexture.prototype._onRatioRescale = function () {
  66447. if (this._sizeRatio) {
  66448. this.resize(this._initialSizeParameter);
  66449. if (!this._adaptiveBlurKernel) {
  66450. this._preparePostProcesses();
  66451. }
  66452. }
  66453. if (this._adaptiveBlurKernel) {
  66454. this._autoComputeBlurKernel();
  66455. }
  66456. };
  66457. MirrorTexture.prototype._updateGammaSpace = function () {
  66458. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  66459. };
  66460. MirrorTexture.prototype._preparePostProcesses = function () {
  66461. this.clearPostProcesses(true);
  66462. if (this._blurKernelX && this._blurKernelY) {
  66463. var engine = this.getScene().getEngine();
  66464. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66465. 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);
  66466. this._blurX.autoClear = false;
  66467. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  66468. this._blurX.inputTexture = this._texture;
  66469. }
  66470. else {
  66471. this._blurX.alwaysForcePOT = true;
  66472. }
  66473. 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);
  66474. this._blurY.autoClear = false;
  66475. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  66476. this.addPostProcess(this._blurX);
  66477. this.addPostProcess(this._blurY);
  66478. }
  66479. else {
  66480. if (this._blurY) {
  66481. this.removePostProcess(this._blurY);
  66482. this._blurY.dispose();
  66483. this._blurY = null;
  66484. }
  66485. if (this._blurX) {
  66486. this.removePostProcess(this._blurX);
  66487. this._blurX.dispose();
  66488. this._blurX = null;
  66489. }
  66490. }
  66491. };
  66492. MirrorTexture.prototype.clone = function () {
  66493. var scene = this.getScene();
  66494. if (!scene) {
  66495. return this;
  66496. }
  66497. var textureSize = this.getSize();
  66498. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  66499. // Base texture
  66500. newTexture.hasAlpha = this.hasAlpha;
  66501. newTexture.level = this.level;
  66502. // Mirror Texture
  66503. newTexture.mirrorPlane = this.mirrorPlane.clone();
  66504. if (this.renderList) {
  66505. newTexture.renderList = this.renderList.slice(0);
  66506. }
  66507. return newTexture;
  66508. };
  66509. MirrorTexture.prototype.serialize = function () {
  66510. if (!this.name) {
  66511. return null;
  66512. }
  66513. var serializationObject = _super.prototype.serialize.call(this);
  66514. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  66515. return serializationObject;
  66516. };
  66517. MirrorTexture.prototype.dispose = function () {
  66518. _super.prototype.dispose.call(this);
  66519. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  66520. };
  66521. return MirrorTexture;
  66522. }(BABYLON.RenderTargetTexture));
  66523. BABYLON.MirrorTexture = MirrorTexture;
  66524. })(BABYLON || (BABYLON = {}));
  66525. //# sourceMappingURL=babylon.mirrorTexture.js.map
  66526. var BABYLON;
  66527. (function (BABYLON) {
  66528. /**
  66529. * Creates a refraction texture used by refraction channel of the standard material.
  66530. * @param name the texture name
  66531. * @param size size of the underlying texture
  66532. * @param scene root scene
  66533. */
  66534. var RefractionTexture = /** @class */ (function (_super) {
  66535. __extends(RefractionTexture, _super);
  66536. function RefractionTexture(name, size, scene, generateMipMaps) {
  66537. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  66538. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  66539. _this.depth = 2.0;
  66540. _this.onBeforeRenderObservable.add(function () {
  66541. scene.clipPlane = _this.refractionPlane;
  66542. });
  66543. _this.onAfterRenderObservable.add(function () {
  66544. delete scene.clipPlane;
  66545. });
  66546. return _this;
  66547. }
  66548. RefractionTexture.prototype.clone = function () {
  66549. var scene = this.getScene();
  66550. if (!scene) {
  66551. return this;
  66552. }
  66553. var textureSize = this.getSize();
  66554. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  66555. // Base texture
  66556. newTexture.hasAlpha = this.hasAlpha;
  66557. newTexture.level = this.level;
  66558. // Refraction Texture
  66559. newTexture.refractionPlane = this.refractionPlane.clone();
  66560. if (this.renderList) {
  66561. newTexture.renderList = this.renderList.slice(0);
  66562. }
  66563. newTexture.depth = this.depth;
  66564. return newTexture;
  66565. };
  66566. RefractionTexture.prototype.serialize = function () {
  66567. if (!this.name) {
  66568. return null;
  66569. }
  66570. var serializationObject = _super.prototype.serialize.call(this);
  66571. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  66572. serializationObject.depth = this.depth;
  66573. return serializationObject;
  66574. };
  66575. return RefractionTexture;
  66576. }(BABYLON.RenderTargetTexture));
  66577. BABYLON.RefractionTexture = RefractionTexture;
  66578. })(BABYLON || (BABYLON = {}));
  66579. //# sourceMappingURL=babylon.refractionTexture.js.map
  66580. var BABYLON;
  66581. (function (BABYLON) {
  66582. /**
  66583. * A class extending {BABYLON.Texture} allowing drawing on a texture
  66584. * @see http://doc.babylonjs.com/how_to/dynamictexture
  66585. */
  66586. var DynamicTexture = /** @class */ (function (_super) {
  66587. __extends(DynamicTexture, _super);
  66588. /**
  66589. * Creates a {BABYLON.DynamicTexture}
  66590. * @param name defines the name of the texture
  66591. * @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
  66592. * @param scene defines the scene where you want the texture
  66593. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  66594. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  66595. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  66596. */
  66597. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66598. if (scene === void 0) { scene = null; }
  66599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66600. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66601. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66602. _this.name = name;
  66603. _this._engine = _this.getScene().getEngine();
  66604. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66605. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66606. _this._generateMipMaps = generateMipMaps;
  66607. if (options.getContext) {
  66608. _this._canvas = options;
  66609. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66610. }
  66611. else {
  66612. _this._canvas = document.createElement("canvas");
  66613. if (options.width || options.width === 0) {
  66614. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66615. }
  66616. else {
  66617. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66618. }
  66619. }
  66620. var textureSize = _this.getSize();
  66621. _this._canvas.width = textureSize.width;
  66622. _this._canvas.height = textureSize.height;
  66623. _this._context = _this._canvas.getContext("2d");
  66624. return _this;
  66625. }
  66626. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  66627. /**
  66628. * Gets the current state of canRescale
  66629. */
  66630. get: function () {
  66631. return true;
  66632. },
  66633. enumerable: true,
  66634. configurable: true
  66635. });
  66636. DynamicTexture.prototype._recreate = function (textureSize) {
  66637. this._canvas.width = textureSize.width;
  66638. this._canvas.height = textureSize.height;
  66639. this.releaseInternalTexture();
  66640. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  66641. };
  66642. /**
  66643. * Scales the texture
  66644. * @param ratio the scale factor to apply to both width and height
  66645. */
  66646. DynamicTexture.prototype.scale = function (ratio) {
  66647. var textureSize = this.getSize();
  66648. textureSize.width *= ratio;
  66649. textureSize.height *= ratio;
  66650. this._recreate(textureSize);
  66651. };
  66652. /**
  66653. * Resizes the texture
  66654. * @param width the new width
  66655. * @param height the new height
  66656. */
  66657. DynamicTexture.prototype.scaleTo = function (width, height) {
  66658. var textureSize = this.getSize();
  66659. textureSize.width = width;
  66660. textureSize.height = height;
  66661. this._recreate(textureSize);
  66662. };
  66663. /**
  66664. * Gets the context of the canvas used by the texture
  66665. * @returns the canvas context of the dynamic texture
  66666. */
  66667. DynamicTexture.prototype.getContext = function () {
  66668. return this._context;
  66669. };
  66670. /**
  66671. * Clears the texture
  66672. */
  66673. DynamicTexture.prototype.clear = function () {
  66674. var size = this.getSize();
  66675. this._context.fillRect(0, 0, size.width, size.height);
  66676. };
  66677. /**
  66678. * Updates the texture
  66679. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66680. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  66681. */
  66682. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  66683. if (premulAlpha === void 0) { premulAlpha = false; }
  66684. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  66685. };
  66686. /**
  66687. * Draws text onto the texture
  66688. * @param text defines the text to be drawn
  66689. * @param x defines the placement of the text from the left
  66690. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  66691. * @param font defines the font to be used with font-style, font-size, font-name
  66692. * @param color defines the color used for the text
  66693. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  66694. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66695. * @param update defines whether texture is immediately update (default is true)
  66696. */
  66697. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  66698. if (update === void 0) { update = true; }
  66699. var size = this.getSize();
  66700. if (clearColor) {
  66701. this._context.fillStyle = clearColor;
  66702. this._context.fillRect(0, 0, size.width, size.height);
  66703. }
  66704. this._context.font = font;
  66705. if (x === null || x === undefined) {
  66706. var textSize = this._context.measureText(text);
  66707. x = (size.width - textSize.width) / 2;
  66708. }
  66709. if (y === null || y === undefined) {
  66710. var fontSize = parseInt((font.replace(/\D/g, '')));
  66711. y = (size.height / 2) + (fontSize / 3.65);
  66712. }
  66713. this._context.fillStyle = color;
  66714. this._context.fillText(text, x, y);
  66715. if (update) {
  66716. this.update(invertY);
  66717. }
  66718. };
  66719. /**
  66720. * Clones the texture
  66721. * @returns the clone of the texture.
  66722. */
  66723. DynamicTexture.prototype.clone = function () {
  66724. var scene = this.getScene();
  66725. if (!scene) {
  66726. return this;
  66727. }
  66728. var textureSize = this.getSize();
  66729. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  66730. // Base texture
  66731. newTexture.hasAlpha = this.hasAlpha;
  66732. newTexture.level = this.level;
  66733. // Dynamic Texture
  66734. newTexture.wrapU = this.wrapU;
  66735. newTexture.wrapV = this.wrapV;
  66736. return newTexture;
  66737. };
  66738. /**
  66739. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  66740. * @returns a serialized dynamic texture object
  66741. */
  66742. DynamicTexture.prototype.serialize = function () {
  66743. var scene = this.getScene();
  66744. if (scene && !scene.isReady()) {
  66745. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  66746. }
  66747. var serializationObject = _super.prototype.serialize.call(this);
  66748. serializationObject.base64String = this._canvas.toDataURL();
  66749. serializationObject.invertY = this._invertY;
  66750. serializationObject.samplingMode = this.samplingMode;
  66751. return serializationObject;
  66752. };
  66753. /** @hidden */
  66754. DynamicTexture.prototype._rebuild = function () {
  66755. this.update();
  66756. };
  66757. return DynamicTexture;
  66758. }(BABYLON.Texture));
  66759. BABYLON.DynamicTexture = DynamicTexture;
  66760. })(BABYLON || (BABYLON = {}));
  66761. //# sourceMappingURL=babylon.dynamicTexture.js.map
  66762. var BABYLON;
  66763. (function (BABYLON) {
  66764. var VideoTexture = /** @class */ (function (_super) {
  66765. __extends(VideoTexture, _super);
  66766. /**
  66767. * Creates a video texture.
  66768. * Sample : https://doc.babylonjs.com/how_to/video_texture
  66769. * @param {string | null} name optional name, will detect from video source, if not defined
  66770. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  66771. * @param {BABYLON.Scene} scene is obviously the current scene.
  66772. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  66773. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  66774. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  66775. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  66776. */
  66777. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  66778. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66779. if (invertY === void 0) { invertY = false; }
  66780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66781. if (settings === void 0) { settings = {
  66782. autoPlay: true,
  66783. loop: true,
  66784. autoUpdateTexture: true,
  66785. }; }
  66786. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66787. _this._onUserActionRequestedObservable = null;
  66788. _this._stillImageCaptured = false;
  66789. _this._poster = false;
  66790. _this._createInternalTexture = function () {
  66791. if (_this._texture != null) {
  66792. if (_this._poster) {
  66793. _this._texture.dispose();
  66794. _this._poster = false;
  66795. }
  66796. else {
  66797. return;
  66798. }
  66799. }
  66800. if (!_this._engine.needPOTTextures ||
  66801. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  66802. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66803. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66804. }
  66805. else {
  66806. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66807. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66808. _this._generateMipMaps = false;
  66809. }
  66810. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  66811. if (!_this.video.autoplay) {
  66812. var oldHandler_1 = _this.video.onplaying;
  66813. var error_1 = false;
  66814. _this.video.onplaying = function () {
  66815. _this.video.onplaying = oldHandler_1;
  66816. _this._texture.isReady = true;
  66817. _this._updateInternalTexture();
  66818. if (!error_1) {
  66819. _this.video.pause();
  66820. }
  66821. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66822. _this.onLoadObservable.notifyObservers(_this);
  66823. }
  66824. };
  66825. var playing = _this.video.play();
  66826. if (playing) {
  66827. playing.then(function () {
  66828. // Everything is good.
  66829. })
  66830. .catch(function () {
  66831. error_1 = true;
  66832. // On Chrome for instance, new policies might prevent playing without user interaction.
  66833. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  66834. _this._onUserActionRequestedObservable.notifyObservers(_this);
  66835. }
  66836. });
  66837. }
  66838. else {
  66839. _this.video.onplaying = oldHandler_1;
  66840. _this._texture.isReady = true;
  66841. _this._updateInternalTexture();
  66842. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66843. _this.onLoadObservable.notifyObservers(_this);
  66844. }
  66845. }
  66846. }
  66847. else {
  66848. _this._texture.isReady = true;
  66849. _this._updateInternalTexture();
  66850. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66851. _this.onLoadObservable.notifyObservers(_this);
  66852. }
  66853. }
  66854. };
  66855. _this.reset = function () {
  66856. if (_this._texture == null) {
  66857. return;
  66858. }
  66859. if (!_this._poster) {
  66860. _this._texture.dispose();
  66861. _this._texture = null;
  66862. }
  66863. };
  66864. _this._updateInternalTexture = function (e) {
  66865. if (_this._texture == null || !_this._texture.isReady) {
  66866. return;
  66867. }
  66868. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  66869. return;
  66870. }
  66871. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  66872. };
  66873. _this._engine = _this.getScene().getEngine();
  66874. _this._generateMipMaps = generateMipMaps;
  66875. _this._samplingMode = samplingMode;
  66876. _this.autoUpdateTexture = settings.autoUpdateTexture;
  66877. _this.name = name || _this._getName(src);
  66878. _this.video = _this._getVideo(src);
  66879. if (settings.poster) {
  66880. _this.video.poster = settings.poster;
  66881. }
  66882. if (settings.autoPlay !== undefined) {
  66883. _this.video.autoplay = settings.autoPlay;
  66884. }
  66885. if (settings.loop !== undefined) {
  66886. _this.video.loop = settings.loop;
  66887. }
  66888. _this.video.setAttribute("playsinline", "");
  66889. _this.video.addEventListener("canplay", _this._createInternalTexture);
  66890. _this.video.addEventListener("paused", _this._updateInternalTexture);
  66891. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  66892. _this.video.addEventListener("emptied", _this.reset);
  66893. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  66894. _this._createInternalTexture();
  66895. }
  66896. if (settings.poster) {
  66897. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  66898. _this._poster = true;
  66899. }
  66900. return _this;
  66901. }
  66902. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  66903. get: function () {
  66904. if (!this._onUserActionRequestedObservable) {
  66905. this._onUserActionRequestedObservable = new BABYLON.Observable();
  66906. }
  66907. return this._onUserActionRequestedObservable;
  66908. },
  66909. enumerable: true,
  66910. configurable: true
  66911. });
  66912. VideoTexture.prototype._getName = function (src) {
  66913. if (src instanceof HTMLVideoElement) {
  66914. return src.currentSrc;
  66915. }
  66916. if (typeof src === "object") {
  66917. return src.toString();
  66918. }
  66919. return src;
  66920. };
  66921. ;
  66922. VideoTexture.prototype._getVideo = function (src) {
  66923. if (src instanceof HTMLVideoElement) {
  66924. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  66925. return src;
  66926. }
  66927. var video = document.createElement("video");
  66928. if (typeof src === "string") {
  66929. BABYLON.Tools.SetCorsBehavior(src, video);
  66930. video.src = src;
  66931. }
  66932. else {
  66933. BABYLON.Tools.SetCorsBehavior(src[0], video);
  66934. src.forEach(function (url) {
  66935. var source = document.createElement("source");
  66936. source.src = url;
  66937. video.appendChild(source);
  66938. });
  66939. }
  66940. return video;
  66941. };
  66942. ;
  66943. /**
  66944. * Internal method to initiate `update`.
  66945. */
  66946. VideoTexture.prototype._rebuild = function () {
  66947. this.update();
  66948. };
  66949. /**
  66950. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  66951. */
  66952. VideoTexture.prototype.update = function () {
  66953. if (!this.autoUpdateTexture) {
  66954. // Expecting user to call `updateTexture` manually
  66955. return;
  66956. }
  66957. this.updateTexture(true);
  66958. };
  66959. /**
  66960. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  66961. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  66962. */
  66963. VideoTexture.prototype.updateTexture = function (isVisible) {
  66964. if (!isVisible) {
  66965. return;
  66966. }
  66967. if (this.video.paused && this._stillImageCaptured) {
  66968. return;
  66969. }
  66970. this._stillImageCaptured = true;
  66971. this._updateInternalTexture();
  66972. };
  66973. /**
  66974. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  66975. * @param url New url.
  66976. */
  66977. VideoTexture.prototype.updateURL = function (url) {
  66978. this.video.src = url;
  66979. };
  66980. VideoTexture.prototype.dispose = function () {
  66981. _super.prototype.dispose.call(this);
  66982. if (this._onUserActionRequestedObservable) {
  66983. this._onUserActionRequestedObservable.clear();
  66984. this._onUserActionRequestedObservable = null;
  66985. }
  66986. this.video.removeEventListener("canplay", this._createInternalTexture);
  66987. this.video.removeEventListener("paused", this._updateInternalTexture);
  66988. this.video.removeEventListener("seeked", this._updateInternalTexture);
  66989. this.video.removeEventListener("emptied", this.reset);
  66990. this.video.pause();
  66991. };
  66992. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  66993. var video = document.createElement("video");
  66994. video.setAttribute('autoplay', '');
  66995. video.setAttribute('muted', '');
  66996. video.setAttribute('playsinline', '');
  66997. var constraintsDeviceId;
  66998. if (constraints && constraints.deviceId) {
  66999. constraintsDeviceId = {
  67000. exact: constraints.deviceId,
  67001. };
  67002. }
  67003. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  67004. if (navigator.mediaDevices) {
  67005. navigator.mediaDevices.getUserMedia({ video: constraints })
  67006. .then(function (stream) {
  67007. if (video.mozSrcObject !== undefined) {
  67008. // hack for Firefox < 19
  67009. video.mozSrcObject = stream;
  67010. }
  67011. else {
  67012. video.srcObject = stream;
  67013. }
  67014. var onPlaying = function () {
  67015. if (onReady) {
  67016. onReady(new VideoTexture("video", video, scene, true, true));
  67017. }
  67018. video.removeEventListener("playing", onPlaying);
  67019. };
  67020. video.addEventListener("playing", onPlaying);
  67021. video.play();
  67022. })
  67023. .catch(function (err) {
  67024. BABYLON.Tools.Error(err.name);
  67025. });
  67026. }
  67027. else {
  67028. navigator.getUserMedia =
  67029. navigator.getUserMedia ||
  67030. navigator.webkitGetUserMedia ||
  67031. navigator.mozGetUserMedia ||
  67032. navigator.msGetUserMedia;
  67033. if (navigator.getUserMedia) {
  67034. navigator.getUserMedia({
  67035. video: {
  67036. deviceId: constraintsDeviceId,
  67037. width: {
  67038. min: (constraints && constraints.minWidth) || 256,
  67039. max: (constraints && constraints.maxWidth) || 640,
  67040. },
  67041. height: {
  67042. min: (constraints && constraints.minHeight) || 256,
  67043. max: (constraints && constraints.maxHeight) || 480,
  67044. },
  67045. },
  67046. }, function (stream) {
  67047. if (video.mozSrcObject !== undefined) {
  67048. // hack for Firefox < 19
  67049. video.mozSrcObject = stream;
  67050. }
  67051. else {
  67052. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  67053. }
  67054. video.play();
  67055. if (onReady) {
  67056. onReady(new VideoTexture("video", video, scene, true, true));
  67057. }
  67058. }, function (e) {
  67059. BABYLON.Tools.Error(e.name);
  67060. });
  67061. }
  67062. }
  67063. };
  67064. return VideoTexture;
  67065. }(BABYLON.Texture));
  67066. BABYLON.VideoTexture = VideoTexture;
  67067. })(BABYLON || (BABYLON = {}));
  67068. //# sourceMappingURL=babylon.videoTexture.js.map
  67069. var BABYLON;
  67070. (function (BABYLON) {
  67071. var RawTexture = /** @class */ (function (_super) {
  67072. __extends(RawTexture, _super);
  67073. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  67074. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67075. if (invertY === void 0) { invertY = false; }
  67076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67077. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67078. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67079. _this.format = format;
  67080. _this._engine = scene.getEngine();
  67081. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  67082. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67083. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67084. return _this;
  67085. }
  67086. RawTexture.prototype.update = function (data) {
  67087. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67088. };
  67089. // Statics
  67090. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67091. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67092. if (invertY === void 0) { invertY = false; }
  67093. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67094. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  67095. };
  67096. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67097. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67098. if (invertY === void 0) { invertY = false; }
  67099. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67100. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67101. };
  67102. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67103. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67104. if (invertY === void 0) { invertY = false; }
  67105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67106. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67107. };
  67108. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67109. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67110. if (invertY === void 0) { invertY = false; }
  67111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67112. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67113. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  67114. };
  67115. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67116. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67117. if (invertY === void 0) { invertY = false; }
  67118. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67119. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67120. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  67121. };
  67122. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67123. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67124. if (invertY === void 0) { invertY = false; }
  67125. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67126. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67127. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  67128. };
  67129. return RawTexture;
  67130. }(BABYLON.Texture));
  67131. BABYLON.RawTexture = RawTexture;
  67132. })(BABYLON || (BABYLON = {}));
  67133. //# sourceMappingURL=babylon.rawTexture.js.map
  67134. var BABYLON;
  67135. (function (BABYLON) {
  67136. /**
  67137. * Class used to store 3D textures containing user data
  67138. */
  67139. var RawTexture3D = /** @class */ (function (_super) {
  67140. __extends(RawTexture3D, _super);
  67141. /**
  67142. * Create a new RawTexture3D
  67143. * @param data defines the data of the texture
  67144. * @param width defines the width of the texture
  67145. * @param height defines the height of the texture
  67146. * @param depth defines the depth of the texture
  67147. * @param format defines the texture format to use
  67148. * @param scene defines the hosting scene
  67149. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  67150. * @param invertY defines if texture must be stored with Y axis inverted
  67151. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  67152. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  67153. */
  67154. function RawTexture3D(data, width, height, depth,
  67155. /** Gets or sets the texture format to use */
  67156. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  67157. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67158. if (invertY === void 0) { invertY = false; }
  67159. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67160. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67161. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67162. _this.format = format;
  67163. _this._engine = scene.getEngine();
  67164. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  67165. _this.is3D = true;
  67166. return _this;
  67167. }
  67168. /**
  67169. * Update the texture with new data
  67170. * @param data defines the data to store in the texture
  67171. */
  67172. RawTexture3D.prototype.update = function (data) {
  67173. if (!this._texture) {
  67174. return;
  67175. }
  67176. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67177. };
  67178. return RawTexture3D;
  67179. }(BABYLON.Texture));
  67180. BABYLON.RawTexture3D = RawTexture3D;
  67181. })(BABYLON || (BABYLON = {}));
  67182. //# sourceMappingURL=babylon.rawTexture3D.js.map
  67183. var BABYLON;
  67184. (function (BABYLON) {
  67185. /**
  67186. * PostProcessManager is used to manage one or more post processes or post process pipelines
  67187. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67188. */
  67189. var PostProcessManager = /** @class */ (function () {
  67190. /**
  67191. * Creates a new instance PostProcess
  67192. * @param scene The scene that the post process is associated with.
  67193. */
  67194. function PostProcessManager(scene) {
  67195. this._vertexBuffers = {};
  67196. this._scene = scene;
  67197. }
  67198. PostProcessManager.prototype._prepareBuffers = function () {
  67199. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  67200. return;
  67201. }
  67202. // VBO
  67203. var vertices = [];
  67204. vertices.push(1, 1);
  67205. vertices.push(-1, 1);
  67206. vertices.push(-1, -1);
  67207. vertices.push(1, -1);
  67208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67209. this._buildIndexBuffer();
  67210. };
  67211. PostProcessManager.prototype._buildIndexBuffer = function () {
  67212. // Indices
  67213. var indices = [];
  67214. indices.push(0);
  67215. indices.push(1);
  67216. indices.push(2);
  67217. indices.push(0);
  67218. indices.push(2);
  67219. indices.push(3);
  67220. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  67221. };
  67222. /**
  67223. * Rebuilds the vertex buffers of the manager.
  67224. */
  67225. PostProcessManager.prototype._rebuild = function () {
  67226. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67227. if (!vb) {
  67228. return;
  67229. }
  67230. vb._rebuild();
  67231. this._buildIndexBuffer();
  67232. };
  67233. // Methods
  67234. /**
  67235. * Prepares a frame to be run through a post process.
  67236. * @param sourceTexture The input texture to the post procesess. (default: null)
  67237. * @param postProcesses An array of post processes to be run. (default: null)
  67238. * @returns True if the post processes were able to be run.
  67239. */
  67240. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  67241. if (sourceTexture === void 0) { sourceTexture = null; }
  67242. if (postProcesses === void 0) { postProcesses = null; }
  67243. var camera = this._scene.activeCamera;
  67244. if (!camera) {
  67245. return false;
  67246. }
  67247. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67248. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67249. return false;
  67250. }
  67251. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  67252. return true;
  67253. };
  67254. /**
  67255. * Manually render a set of post processes to a texture.
  67256. * @param postProcesses An array of post processes to be run.
  67257. * @param targetTexture The target texture to render to.
  67258. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  67259. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  67260. * @param lodLevel defines which lod of the texture to render to
  67261. */
  67262. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  67263. if (targetTexture === void 0) { targetTexture = null; }
  67264. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67265. if (faceIndex === void 0) { faceIndex = 0; }
  67266. if (lodLevel === void 0) { lodLevel = 0; }
  67267. var engine = this._scene.getEngine();
  67268. for (var index = 0; index < postProcesses.length; index++) {
  67269. if (index < postProcesses.length - 1) {
  67270. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  67271. }
  67272. else {
  67273. if (targetTexture) {
  67274. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  67275. }
  67276. else {
  67277. engine.restoreDefaultFramebuffer();
  67278. }
  67279. }
  67280. var pp = postProcesses[index];
  67281. var effect = pp.apply();
  67282. if (effect) {
  67283. pp.onBeforeRenderObservable.notifyObservers(effect);
  67284. // VBOs
  67285. this._prepareBuffers();
  67286. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67287. // Draw order
  67288. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67289. pp.onAfterRenderObservable.notifyObservers(effect);
  67290. }
  67291. }
  67292. // Restore depth buffer
  67293. engine.setDepthBuffer(true);
  67294. engine.setDepthWrite(true);
  67295. };
  67296. /**
  67297. * Finalize the result of the output of the postprocesses.
  67298. * @param doNotPresent If true the result will not be displayed to the screen.
  67299. * @param targetTexture The target texture to render to.
  67300. * @param faceIndex The index of the face to bind the target texture to.
  67301. * @param postProcesses The array of post processes to render.
  67302. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  67303. */
  67304. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  67305. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67306. var camera = this._scene.activeCamera;
  67307. if (!camera) {
  67308. return;
  67309. }
  67310. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67311. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67312. return;
  67313. }
  67314. var engine = this._scene.getEngine();
  67315. for (var index = 0, len = postProcesses.length; index < len; index++) {
  67316. var pp = postProcesses[index];
  67317. if (index < len - 1) {
  67318. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  67319. }
  67320. else {
  67321. if (targetTexture) {
  67322. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  67323. pp._outputTexture = targetTexture;
  67324. }
  67325. else {
  67326. engine.restoreDefaultFramebuffer();
  67327. pp._outputTexture = null;
  67328. }
  67329. }
  67330. if (doNotPresent) {
  67331. break;
  67332. }
  67333. var effect = pp.apply();
  67334. if (effect) {
  67335. pp.onBeforeRenderObservable.notifyObservers(effect);
  67336. // VBOs
  67337. this._prepareBuffers();
  67338. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67339. // Draw order
  67340. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67341. pp.onAfterRenderObservable.notifyObservers(effect);
  67342. }
  67343. }
  67344. // Restore states
  67345. engine.setDepthBuffer(true);
  67346. engine.setDepthWrite(true);
  67347. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67348. };
  67349. /**
  67350. * Disposes of the post process manager.
  67351. */
  67352. PostProcessManager.prototype.dispose = function () {
  67353. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67354. if (buffer) {
  67355. buffer.dispose();
  67356. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67357. }
  67358. if (this._indexBuffer) {
  67359. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67360. this._indexBuffer = null;
  67361. }
  67362. };
  67363. return PostProcessManager;
  67364. }());
  67365. BABYLON.PostProcessManager = PostProcessManager;
  67366. })(BABYLON || (BABYLON = {}));
  67367. //# sourceMappingURL=babylon.postProcessManager.js.map
  67368. var BABYLON;
  67369. (function (BABYLON) {
  67370. /**
  67371. * PostProcess can be used to apply a shader to a texture after it has been rendered
  67372. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67373. */
  67374. var PostProcess = /** @class */ (function () {
  67375. /**
  67376. * Creates a new instance PostProcess
  67377. * @param name The name of the PostProcess.
  67378. * @param fragmentUrl The url of the fragment shader to be used.
  67379. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  67380. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  67381. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  67382. * @param camera The camera to apply the render pass to.
  67383. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67384. * @param engine The engine which the post process will be applied. (default: current engine)
  67385. * @param reusable If the post process can be reused on the same frame. (default: false)
  67386. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  67387. * @param textureType Type of textures used when performing the post process. (default: 0)
  67388. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  67389. * @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
  67390. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  67391. */
  67392. function PostProcess(
  67393. /** Name of the PostProcess. */
  67394. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  67395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  67396. if (defines === void 0) { defines = null; }
  67397. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67398. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  67399. if (blockCompilation === void 0) { blockCompilation = false; }
  67400. this.name = name;
  67401. /**
  67402. * Width of the texture to apply the post process on
  67403. */
  67404. this.width = -1;
  67405. /**
  67406. * Height of the texture to apply the post process on
  67407. */
  67408. this.height = -1;
  67409. /**
  67410. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  67411. */
  67412. this._outputTexture = null;
  67413. /**
  67414. * If the buffer needs to be cleared before applying the post process. (default: true)
  67415. * Should be set to false if shader will overwrite all previous pixels.
  67416. */
  67417. this.autoClear = true;
  67418. /**
  67419. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  67420. */
  67421. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  67422. /**
  67423. * Animations to be used for the post processing
  67424. */
  67425. this.animations = new Array();
  67426. /**
  67427. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  67428. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  67429. */
  67430. this.enablePixelPerfectMode = false;
  67431. /**
  67432. * Force the postprocess to be applied without taking in account viewport
  67433. */
  67434. this.forceFullscreenViewport = true;
  67435. /**
  67436. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  67437. *
  67438. * | Value | Type | Description |
  67439. * | ----- | ----------------------------------- | ----------- |
  67440. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  67441. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  67442. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  67443. *
  67444. */
  67445. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  67446. /**
  67447. * Force textures to be a power of two (default: false)
  67448. */
  67449. this.alwaysForcePOT = false;
  67450. /**
  67451. * Number of sample textures (default: 1)
  67452. */
  67453. this.samples = 1;
  67454. /**
  67455. * Modify the scale of the post process to be the same as the viewport (default: false)
  67456. */
  67457. this.adaptScaleToCurrentViewport = false;
  67458. this._reusable = false;
  67459. /**
  67460. * Smart array of input and output textures for the post process.
  67461. */
  67462. this._textures = new BABYLON.SmartArray(2);
  67463. /**
  67464. * The index in _textures that corresponds to the output texture.
  67465. */
  67466. this._currentRenderTextureInd = 0;
  67467. this._scaleRatio = new BABYLON.Vector2(1, 1);
  67468. this._texelSize = BABYLON.Vector2.Zero();
  67469. // Events
  67470. /**
  67471. * An event triggered when the postprocess is activated.
  67472. */
  67473. this.onActivateObservable = new BABYLON.Observable();
  67474. /**
  67475. * An event triggered when the postprocess changes its size.
  67476. */
  67477. this.onSizeChangedObservable = new BABYLON.Observable();
  67478. /**
  67479. * An event triggered when the postprocess applies its effect.
  67480. */
  67481. this.onApplyObservable = new BABYLON.Observable();
  67482. /**
  67483. * An event triggered before rendering the postprocess
  67484. */
  67485. this.onBeforeRenderObservable = new BABYLON.Observable();
  67486. /**
  67487. * An event triggered after rendering the postprocess
  67488. */
  67489. this.onAfterRenderObservable = new BABYLON.Observable();
  67490. if (camera != null) {
  67491. this._camera = camera;
  67492. this._scene = camera.getScene();
  67493. camera.attachPostProcess(this);
  67494. this._engine = this._scene.getEngine();
  67495. this._scene.postProcesses.push(this);
  67496. }
  67497. else if (engine) {
  67498. this._engine = engine;
  67499. this._engine.postProcesses.push(this);
  67500. }
  67501. this._options = options;
  67502. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  67503. this._reusable = reusable || false;
  67504. this._textureType = textureType;
  67505. this._samplers = samplers || [];
  67506. this._samplers.push("textureSampler");
  67507. this._fragmentUrl = fragmentUrl;
  67508. this._vertexUrl = vertexUrl;
  67509. this._parameters = parameters || [];
  67510. this._parameters.push("scale");
  67511. this._indexParameters = indexParameters;
  67512. if (!blockCompilation) {
  67513. this.updateEffect(defines);
  67514. }
  67515. }
  67516. Object.defineProperty(PostProcess.prototype, "onActivate", {
  67517. /**
  67518. * A function that is added to the onActivateObservable
  67519. */
  67520. set: function (callback) {
  67521. if (this._onActivateObserver) {
  67522. this.onActivateObservable.remove(this._onActivateObserver);
  67523. }
  67524. if (callback) {
  67525. this._onActivateObserver = this.onActivateObservable.add(callback);
  67526. }
  67527. },
  67528. enumerable: true,
  67529. configurable: true
  67530. });
  67531. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  67532. /**
  67533. * A function that is added to the onSizeChangedObservable
  67534. */
  67535. set: function (callback) {
  67536. if (this._onSizeChangedObserver) {
  67537. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  67538. }
  67539. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  67540. },
  67541. enumerable: true,
  67542. configurable: true
  67543. });
  67544. Object.defineProperty(PostProcess.prototype, "onApply", {
  67545. /**
  67546. * A function that is added to the onApplyObservable
  67547. */
  67548. set: function (callback) {
  67549. if (this._onApplyObserver) {
  67550. this.onApplyObservable.remove(this._onApplyObserver);
  67551. }
  67552. this._onApplyObserver = this.onApplyObservable.add(callback);
  67553. },
  67554. enumerable: true,
  67555. configurable: true
  67556. });
  67557. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  67558. /**
  67559. * A function that is added to the onBeforeRenderObservable
  67560. */
  67561. set: function (callback) {
  67562. if (this._onBeforeRenderObserver) {
  67563. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67564. }
  67565. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67566. },
  67567. enumerable: true,
  67568. configurable: true
  67569. });
  67570. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  67571. /**
  67572. * A function that is added to the onAfterRenderObservable
  67573. */
  67574. set: function (callback) {
  67575. if (this._onAfterRenderObserver) {
  67576. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67577. }
  67578. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67579. },
  67580. enumerable: true,
  67581. configurable: true
  67582. });
  67583. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  67584. /**
  67585. * 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
  67586. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  67587. */
  67588. get: function () {
  67589. return this._textures.data[this._currentRenderTextureInd];
  67590. },
  67591. set: function (value) {
  67592. this._forcedOutputTexture = value;
  67593. },
  67594. enumerable: true,
  67595. configurable: true
  67596. });
  67597. /**
  67598. * Gets the camera which post process is applied to.
  67599. * @returns The camera the post process is applied to.
  67600. */
  67601. PostProcess.prototype.getCamera = function () {
  67602. return this._camera;
  67603. };
  67604. Object.defineProperty(PostProcess.prototype, "texelSize", {
  67605. /**
  67606. * Gets the texel size of the postprocess.
  67607. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  67608. */
  67609. get: function () {
  67610. if (this._shareOutputWithPostProcess) {
  67611. return this._shareOutputWithPostProcess.texelSize;
  67612. }
  67613. if (this._forcedOutputTexture) {
  67614. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67615. }
  67616. return this._texelSize;
  67617. },
  67618. enumerable: true,
  67619. configurable: true
  67620. });
  67621. /**
  67622. * Gets the engine which this post process belongs to.
  67623. * @returns The engine the post process was enabled with.
  67624. */
  67625. PostProcess.prototype.getEngine = function () {
  67626. return this._engine;
  67627. };
  67628. /**
  67629. * The effect that is created when initializing the post process.
  67630. * @returns The created effect corrisponding the the postprocess.
  67631. */
  67632. PostProcess.prototype.getEffect = function () {
  67633. return this._effect;
  67634. };
  67635. /**
  67636. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  67637. * @param postProcess The post process to share the output with.
  67638. * @returns This post process.
  67639. */
  67640. PostProcess.prototype.shareOutputWith = function (postProcess) {
  67641. this._disposeTextures();
  67642. this._shareOutputWithPostProcess = postProcess;
  67643. return this;
  67644. };
  67645. /**
  67646. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  67647. * This should be called if the post process that shares output with this post process is disabled/disposed.
  67648. */
  67649. PostProcess.prototype.useOwnOutput = function () {
  67650. if (this._textures.length == 0) {
  67651. this._textures = new BABYLON.SmartArray(2);
  67652. }
  67653. this._shareOutputWithPostProcess = null;
  67654. };
  67655. /**
  67656. * Updates the effect with the current post process compile time values and recompiles the shader.
  67657. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  67658. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  67659. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  67660. * @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
  67661. * @param onCompiled Called when the shader has been compiled.
  67662. * @param onError Called if there is an error when compiling a shader.
  67663. */
  67664. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  67665. if (defines === void 0) { defines = null; }
  67666. if (uniforms === void 0) { uniforms = null; }
  67667. if (samplers === void 0) { samplers = null; }
  67668. 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);
  67669. };
  67670. /**
  67671. * The post process is reusable if it can be used multiple times within one frame.
  67672. * @returns If the post process is reusable
  67673. */
  67674. PostProcess.prototype.isReusable = function () {
  67675. return this._reusable;
  67676. };
  67677. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  67678. PostProcess.prototype.markTextureDirty = function () {
  67679. this.width = -1;
  67680. };
  67681. /**
  67682. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  67683. * 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.
  67684. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  67685. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  67686. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  67687. * @returns The target texture that was bound to be written to.
  67688. */
  67689. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  67690. var _this = this;
  67691. if (sourceTexture === void 0) { sourceTexture = null; }
  67692. camera = camera || this._camera;
  67693. var scene = camera.getScene();
  67694. var engine = scene.getEngine();
  67695. var maxSize = engine.getCaps().maxTextureSize;
  67696. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  67697. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  67698. // 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
  67699. var webVRCamera = camera.parent;
  67700. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  67701. requiredWidth /= 2;
  67702. }
  67703. var desiredWidth = (this._options.width || requiredWidth);
  67704. var desiredHeight = this._options.height || requiredHeight;
  67705. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  67706. if (this.adaptScaleToCurrentViewport) {
  67707. var currentViewport = engine.currentViewport;
  67708. if (currentViewport) {
  67709. desiredWidth *= currentViewport.width;
  67710. desiredHeight *= currentViewport.height;
  67711. }
  67712. }
  67713. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  67714. if (!this._options.width) {
  67715. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  67716. }
  67717. if (!this._options.height) {
  67718. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  67719. }
  67720. }
  67721. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  67722. if (this._textures.length > 0) {
  67723. for (var i = 0; i < this._textures.length; i++) {
  67724. this._engine._releaseTexture(this._textures.data[i]);
  67725. }
  67726. this._textures.reset();
  67727. }
  67728. this.width = desiredWidth;
  67729. this.height = desiredHeight;
  67730. var textureSize = { width: this.width, height: this.height };
  67731. var textureOptions = {
  67732. generateMipMaps: false,
  67733. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  67734. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  67735. samplingMode: this.renderTargetSamplingMode,
  67736. type: this._textureType
  67737. };
  67738. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67739. if (this._reusable) {
  67740. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67741. }
  67742. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  67743. this.onSizeChangedObservable.notifyObservers(this);
  67744. }
  67745. this._textures.forEach(function (texture) {
  67746. if (texture.samples !== _this.samples) {
  67747. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  67748. }
  67749. });
  67750. }
  67751. var target;
  67752. if (this._shareOutputWithPostProcess) {
  67753. target = this._shareOutputWithPostProcess.inputTexture;
  67754. }
  67755. else if (this._forcedOutputTexture) {
  67756. target = this._forcedOutputTexture;
  67757. this.width = this._forcedOutputTexture.width;
  67758. this.height = this._forcedOutputTexture.height;
  67759. }
  67760. else {
  67761. target = this.inputTexture;
  67762. }
  67763. // Bind the input of this post process to be used as the output of the previous post process.
  67764. if (this.enablePixelPerfectMode) {
  67765. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  67766. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  67767. }
  67768. else {
  67769. this._scaleRatio.copyFromFloats(1, 1);
  67770. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  67771. }
  67772. this.onActivateObservable.notifyObservers(camera);
  67773. // Clear
  67774. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  67775. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  67776. }
  67777. if (this._reusable) {
  67778. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  67779. }
  67780. return target;
  67781. };
  67782. Object.defineProperty(PostProcess.prototype, "isSupported", {
  67783. /**
  67784. * If the post process is supported.
  67785. */
  67786. get: function () {
  67787. return this._effect.isSupported;
  67788. },
  67789. enumerable: true,
  67790. configurable: true
  67791. });
  67792. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  67793. /**
  67794. * The aspect ratio of the output texture.
  67795. */
  67796. get: function () {
  67797. if (this._shareOutputWithPostProcess) {
  67798. return this._shareOutputWithPostProcess.aspectRatio;
  67799. }
  67800. if (this._forcedOutputTexture) {
  67801. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  67802. }
  67803. return this.width / this.height;
  67804. },
  67805. enumerable: true,
  67806. configurable: true
  67807. });
  67808. /**
  67809. * Get a value indicating if the post-process is ready to be used
  67810. * @returns true if the post-process is ready (shader is compiled)
  67811. */
  67812. PostProcess.prototype.isReady = function () {
  67813. return this._effect && this._effect.isReady();
  67814. };
  67815. /**
  67816. * Binds all textures and uniforms to the shader, this will be run on every pass.
  67817. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  67818. */
  67819. PostProcess.prototype.apply = function () {
  67820. // Check
  67821. if (!this._effect || !this._effect.isReady())
  67822. return null;
  67823. // States
  67824. this._engine.enableEffect(this._effect);
  67825. this._engine.setState(false);
  67826. this._engine.setDepthBuffer(false);
  67827. this._engine.setDepthWrite(false);
  67828. // Alpha
  67829. this._engine.setAlphaMode(this.alphaMode);
  67830. if (this.alphaConstants) {
  67831. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  67832. }
  67833. // Bind the output texture of the preivous post process as the input to this post process.
  67834. var source;
  67835. if (this._shareOutputWithPostProcess) {
  67836. source = this._shareOutputWithPostProcess.inputTexture;
  67837. }
  67838. else if (this._forcedOutputTexture) {
  67839. source = this._forcedOutputTexture;
  67840. }
  67841. else {
  67842. source = this.inputTexture;
  67843. }
  67844. this._effect._bindTexture("textureSampler", source);
  67845. // Parameters
  67846. this._effect.setVector2("scale", this._scaleRatio);
  67847. this.onApplyObservable.notifyObservers(this._effect);
  67848. return this._effect;
  67849. };
  67850. PostProcess.prototype._disposeTextures = function () {
  67851. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  67852. return;
  67853. }
  67854. if (this._textures.length > 0) {
  67855. for (var i = 0; i < this._textures.length; i++) {
  67856. this._engine._releaseTexture(this._textures.data[i]);
  67857. }
  67858. }
  67859. this._textures.dispose();
  67860. };
  67861. /**
  67862. * Disposes the post process.
  67863. * @param camera The camera to dispose the post process on.
  67864. */
  67865. PostProcess.prototype.dispose = function (camera) {
  67866. camera = camera || this._camera;
  67867. this._disposeTextures();
  67868. if (this._scene) {
  67869. var index_1 = this._scene.postProcesses.indexOf(this);
  67870. if (index_1 !== -1) {
  67871. this._scene.postProcesses.splice(index_1, 1);
  67872. }
  67873. }
  67874. else {
  67875. var index_2 = this._engine.postProcesses.indexOf(this);
  67876. if (index_2 !== -1) {
  67877. this._engine.postProcesses.splice(index_2, 1);
  67878. }
  67879. }
  67880. if (!camera) {
  67881. return;
  67882. }
  67883. camera.detachPostProcess(this);
  67884. var index = camera._postProcesses.indexOf(this);
  67885. if (index === 0 && camera._postProcesses.length > 0) {
  67886. var firstPostProcess = this._camera._getFirstPostProcess();
  67887. if (firstPostProcess) {
  67888. firstPostProcess.markTextureDirty();
  67889. }
  67890. }
  67891. this.onActivateObservable.clear();
  67892. this.onAfterRenderObservable.clear();
  67893. this.onApplyObservable.clear();
  67894. this.onBeforeRenderObservable.clear();
  67895. this.onSizeChangedObservable.clear();
  67896. };
  67897. return PostProcess;
  67898. }());
  67899. BABYLON.PostProcess = PostProcess;
  67900. })(BABYLON || (BABYLON = {}));
  67901. //# sourceMappingURL=babylon.postProcess.js.map
  67902. var BABYLON;
  67903. (function (BABYLON) {
  67904. var PassPostProcess = /** @class */ (function (_super) {
  67905. __extends(PassPostProcess, _super);
  67906. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67907. if (camera === void 0) { camera = null; }
  67908. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67909. if (blockCompilation === void 0) { blockCompilation = false; }
  67910. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  67911. }
  67912. return PassPostProcess;
  67913. }(BABYLON.PostProcess));
  67914. BABYLON.PassPostProcess = PassPostProcess;
  67915. })(BABYLON || (BABYLON = {}));
  67916. //# sourceMappingURL=babylon.passPostProcess.js.map
  67917. var __assign = (this && this.__assign) || Object.assign || function(t) {
  67918. for (var s, i = 1, n = arguments.length; i < n; i++) {
  67919. s = arguments[i];
  67920. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  67921. t[p] = s[p];
  67922. }
  67923. return t;
  67924. };
  67925. var BABYLON;
  67926. (function (BABYLON) {
  67927. /**
  67928. * Default implementation IShadowGenerator.
  67929. * This is the main object responsible of generating shadows in the framework.
  67930. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  67931. */
  67932. var ShadowGenerator = /** @class */ (function () {
  67933. /**
  67934. * Creates a ShadowGenerator object.
  67935. * A ShadowGenerator is the required tool to use the shadows.
  67936. * Each light casting shadows needs to use its own ShadowGenerator.
  67937. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  67938. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  67939. * @param light The light object generating the shadows.
  67940. * @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.
  67941. */
  67942. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  67943. this._bias = 0.00005;
  67944. this._normalBias = 0;
  67945. this._blurBoxOffset = 1;
  67946. this._blurScale = 2;
  67947. this._blurKernel = 1;
  67948. this._useKernelBlur = false;
  67949. this._filter = ShadowGenerator.FILTER_NONE;
  67950. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  67951. this._contactHardeningLightSizeUVRatio = 0.1;
  67952. this._darkness = 0;
  67953. this._transparencyShadow = false;
  67954. /**
  67955. * Controls the extent to which the shadows fade out at the edge of the frustum
  67956. * Used only by directionals and spots
  67957. */
  67958. this.frustumEdgeFalloff = 0;
  67959. /**
  67960. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  67961. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  67962. * It might on the other hand introduce peter panning.
  67963. */
  67964. this.forceBackFacesOnly = false;
  67965. this._lightDirection = BABYLON.Vector3.Zero();
  67966. this._viewMatrix = BABYLON.Matrix.Zero();
  67967. this._projectionMatrix = BABYLON.Matrix.Zero();
  67968. this._transformMatrix = BABYLON.Matrix.Zero();
  67969. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67970. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67971. this._currentFaceIndex = 0;
  67972. this._currentFaceIndexCache = 0;
  67973. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  67974. this._mapSize = mapSize;
  67975. this._light = light;
  67976. this._scene = light.getScene();
  67977. light._shadowGenerator = this;
  67978. // Texture type fallback from float to int if not supported.
  67979. var caps = this._scene.getEngine().getCaps();
  67980. if (!useFullFloatFirst) {
  67981. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67982. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67983. }
  67984. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67985. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67986. }
  67987. else {
  67988. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67989. }
  67990. }
  67991. else {
  67992. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67993. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67994. }
  67995. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67996. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67997. }
  67998. else {
  67999. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68000. }
  68001. }
  68002. this._initializeGenerator();
  68003. this._applyFilterValues();
  68004. }
  68005. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  68006. /**
  68007. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  68008. */
  68009. get: function () {
  68010. return this._bias;
  68011. },
  68012. /**
  68013. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  68014. */
  68015. set: function (bias) {
  68016. this._bias = bias;
  68017. },
  68018. enumerable: true,
  68019. configurable: true
  68020. });
  68021. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  68022. /**
  68023. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68024. */
  68025. get: function () {
  68026. return this._normalBias;
  68027. },
  68028. /**
  68029. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68030. */
  68031. set: function (normalBias) {
  68032. this._normalBias = normalBias;
  68033. },
  68034. enumerable: true,
  68035. configurable: true
  68036. });
  68037. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  68038. /**
  68039. * Gets the blur box offset: offset applied during the blur pass.
  68040. * Only usefull if useKernelBlur = false
  68041. */
  68042. get: function () {
  68043. return this._blurBoxOffset;
  68044. },
  68045. /**
  68046. * Sets the blur box offset: offset applied during the blur pass.
  68047. * Only usefull if useKernelBlur = false
  68048. */
  68049. set: function (value) {
  68050. if (this._blurBoxOffset === value) {
  68051. return;
  68052. }
  68053. this._blurBoxOffset = value;
  68054. this._disposeBlurPostProcesses();
  68055. },
  68056. enumerable: true,
  68057. configurable: true
  68058. });
  68059. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  68060. /**
  68061. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  68062. * 2 means half of the size.
  68063. */
  68064. get: function () {
  68065. return this._blurScale;
  68066. },
  68067. /**
  68068. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  68069. * 2 means half of the size.
  68070. */
  68071. set: function (value) {
  68072. if (this._blurScale === value) {
  68073. return;
  68074. }
  68075. this._blurScale = value;
  68076. this._disposeBlurPostProcesses();
  68077. },
  68078. enumerable: true,
  68079. configurable: true
  68080. });
  68081. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  68082. /**
  68083. * Gets the blur kernel: kernel size of the blur pass.
  68084. * Only usefull if useKernelBlur = true
  68085. */
  68086. get: function () {
  68087. return this._blurKernel;
  68088. },
  68089. /**
  68090. * Sets the blur kernel: kernel size of the blur pass.
  68091. * Only usefull if useKernelBlur = true
  68092. */
  68093. set: function (value) {
  68094. if (this._blurKernel === value) {
  68095. return;
  68096. }
  68097. this._blurKernel = value;
  68098. this._disposeBlurPostProcesses();
  68099. },
  68100. enumerable: true,
  68101. configurable: true
  68102. });
  68103. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  68104. /**
  68105. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  68106. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68107. */
  68108. get: function () {
  68109. return this._useKernelBlur;
  68110. },
  68111. /**
  68112. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  68113. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68114. */
  68115. set: function (value) {
  68116. if (this._useKernelBlur === value) {
  68117. return;
  68118. }
  68119. this._useKernelBlur = value;
  68120. this._disposeBlurPostProcesses();
  68121. },
  68122. enumerable: true,
  68123. configurable: true
  68124. });
  68125. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  68126. /**
  68127. * Gets the depth scale used in ESM mode.
  68128. */
  68129. get: function () {
  68130. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  68131. },
  68132. /**
  68133. * Sets the depth scale used in ESM mode.
  68134. * This can override the scale stored on the light.
  68135. */
  68136. set: function (value) {
  68137. this._depthScale = value;
  68138. },
  68139. enumerable: true,
  68140. configurable: true
  68141. });
  68142. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  68143. /**
  68144. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  68145. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68146. */
  68147. get: function () {
  68148. return this._filter;
  68149. },
  68150. /**
  68151. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  68152. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68153. */
  68154. set: function (value) {
  68155. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  68156. if (this._light.needCube()) {
  68157. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68158. this.useExponentialShadowMap = true;
  68159. return;
  68160. }
  68161. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68162. this.useCloseExponentialShadowMap = true;
  68163. return;
  68164. }
  68165. // PCF on cubemap would also be expensive
  68166. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68167. this.usePoissonSampling = true;
  68168. return;
  68169. }
  68170. }
  68171. // Weblg1 fallback for PCF.
  68172. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68173. if (this._scene.getEngine().webGLVersion === 1) {
  68174. this.usePoissonSampling = true;
  68175. return;
  68176. }
  68177. }
  68178. if (this._filter === value) {
  68179. return;
  68180. }
  68181. this._filter = value;
  68182. this._disposeBlurPostProcesses();
  68183. this._applyFilterValues();
  68184. this._light._markMeshesAsLightDirty();
  68185. },
  68186. enumerable: true,
  68187. configurable: true
  68188. });
  68189. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  68190. /**
  68191. * Gets if the current filter is set to Poisson Sampling.
  68192. */
  68193. get: function () {
  68194. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  68195. },
  68196. /**
  68197. * Sets the current filter to Poisson Sampling.
  68198. */
  68199. set: function (value) {
  68200. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  68201. return;
  68202. }
  68203. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  68204. },
  68205. enumerable: true,
  68206. configurable: true
  68207. });
  68208. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  68209. /**
  68210. * Gets if the current filter is set to VSM.
  68211. * DEPRECATED. Should use useExponentialShadowMap instead.
  68212. */
  68213. get: function () {
  68214. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68215. return this.useExponentialShadowMap;
  68216. },
  68217. /**
  68218. * Sets the current filter is to VSM.
  68219. * DEPRECATED. Should use useExponentialShadowMap instead.
  68220. */
  68221. set: function (value) {
  68222. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68223. this.useExponentialShadowMap = value;
  68224. },
  68225. enumerable: true,
  68226. configurable: true
  68227. });
  68228. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  68229. /**
  68230. * Gets if the current filter is set to blurred VSM.
  68231. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68232. */
  68233. get: function () {
  68234. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68235. return this.useBlurExponentialShadowMap;
  68236. },
  68237. /**
  68238. * Sets the current filter is to blurred VSM.
  68239. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68240. */
  68241. set: function (value) {
  68242. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68243. this.useBlurExponentialShadowMap = value;
  68244. },
  68245. enumerable: true,
  68246. configurable: true
  68247. });
  68248. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  68249. /**
  68250. * Gets if the current filter is set to ESM.
  68251. */
  68252. get: function () {
  68253. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  68254. },
  68255. /**
  68256. * Sets the current filter is to ESM.
  68257. */
  68258. set: function (value) {
  68259. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  68260. return;
  68261. }
  68262. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68263. },
  68264. enumerable: true,
  68265. configurable: true
  68266. });
  68267. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  68268. /**
  68269. * Gets if the current filter is set to filtered ESM.
  68270. */
  68271. get: function () {
  68272. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  68273. },
  68274. /**
  68275. * Gets if the current filter is set to filtered ESM.
  68276. */
  68277. set: function (value) {
  68278. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68279. return;
  68280. }
  68281. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68282. },
  68283. enumerable: true,
  68284. configurable: true
  68285. });
  68286. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  68287. /**
  68288. * Gets if the current filter is set to "close ESM" (using the inverse of the
  68289. * exponential to prevent steep falloff artifacts).
  68290. */
  68291. get: function () {
  68292. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  68293. },
  68294. /**
  68295. * Sets the current filter to "close ESM" (using the inverse of the
  68296. * exponential to prevent steep falloff artifacts).
  68297. */
  68298. set: function (value) {
  68299. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  68300. return;
  68301. }
  68302. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68303. },
  68304. enumerable: true,
  68305. configurable: true
  68306. });
  68307. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  68308. /**
  68309. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  68310. * exponential to prevent steep falloff artifacts).
  68311. */
  68312. get: function () {
  68313. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  68314. },
  68315. /**
  68316. * Sets the current filter to filtered "close ESM" (using the inverse of the
  68317. * exponential to prevent steep falloff artifacts).
  68318. */
  68319. set: function (value) {
  68320. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68321. return;
  68322. }
  68323. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68324. },
  68325. enumerable: true,
  68326. configurable: true
  68327. });
  68328. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  68329. /**
  68330. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  68331. */
  68332. get: function () {
  68333. return this.filter === ShadowGenerator.FILTER_PCF;
  68334. },
  68335. /**
  68336. * Sets the current filter to "PCF" (percentage closer filtering).
  68337. */
  68338. set: function (value) {
  68339. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  68340. return;
  68341. }
  68342. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  68343. },
  68344. enumerable: true,
  68345. configurable: true
  68346. });
  68347. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  68348. /**
  68349. * Gets the PCF or PCSS Quality.
  68350. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68351. */
  68352. get: function () {
  68353. return this._filteringQuality;
  68354. },
  68355. /**
  68356. * Sets the PCF or PCSS Quality.
  68357. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68358. */
  68359. set: function (filteringQuality) {
  68360. this._filteringQuality = filteringQuality;
  68361. },
  68362. enumerable: true,
  68363. configurable: true
  68364. });
  68365. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  68366. /**
  68367. * Gets if the current filter is set to "PCSS" (contact hardening).
  68368. */
  68369. get: function () {
  68370. return this.filter === ShadowGenerator.FILTER_PCSS;
  68371. },
  68372. /**
  68373. * Sets the current filter to "PCSS" (contact hardening).
  68374. */
  68375. set: function (value) {
  68376. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  68377. return;
  68378. }
  68379. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  68380. },
  68381. enumerable: true,
  68382. configurable: true
  68383. });
  68384. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  68385. /**
  68386. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  68387. * Using a ratio helps keeping shape stability independently of the map size.
  68388. *
  68389. * It does not account for the light projection as it was having too much
  68390. * instability during the light setup or during light position changes.
  68391. *
  68392. * Only valid if useContactHardeningShadow is true.
  68393. */
  68394. get: function () {
  68395. return this._contactHardeningLightSizeUVRatio;
  68396. },
  68397. /**
  68398. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  68399. * Using a ratio helps keeping shape stability independently of the map size.
  68400. *
  68401. * It does not account for the light projection as it was having too much
  68402. * instability during the light setup or during light position changes.
  68403. *
  68404. * Only valid if useContactHardeningShadow is true.
  68405. */
  68406. set: function (contactHardeningLightSizeUVRatio) {
  68407. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  68408. },
  68409. enumerable: true,
  68410. configurable: true
  68411. });
  68412. /**
  68413. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  68414. * 0 means strongest and 1 would means no shadow.
  68415. * @returns the darkness.
  68416. */
  68417. ShadowGenerator.prototype.getDarkness = function () {
  68418. return this._darkness;
  68419. };
  68420. /**
  68421. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  68422. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  68423. * @returns the shadow generator allowing fluent coding.
  68424. */
  68425. ShadowGenerator.prototype.setDarkness = function (darkness) {
  68426. if (darkness >= 1.0)
  68427. this._darkness = 1.0;
  68428. else if (darkness <= 0.0)
  68429. this._darkness = 0.0;
  68430. else
  68431. this._darkness = darkness;
  68432. return this;
  68433. };
  68434. /**
  68435. * Sets the ability to have transparent shadow (boolean).
  68436. * @param transparent True if transparent else False
  68437. * @returns the shadow generator allowing fluent coding
  68438. */
  68439. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  68440. this._transparencyShadow = transparent;
  68441. return this;
  68442. };
  68443. /**
  68444. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  68445. * @returns The render target texture if present otherwise, null
  68446. */
  68447. ShadowGenerator.prototype.getShadowMap = function () {
  68448. return this._shadowMap;
  68449. };
  68450. /**
  68451. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  68452. * @returns The render target texture if the shadow map is present otherwise, null
  68453. */
  68454. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  68455. if (this._shadowMap2) {
  68456. return this._shadowMap2;
  68457. }
  68458. return this._shadowMap;
  68459. };
  68460. /**
  68461. * Helper function to add a mesh and its descendants to the list of shadow casters.
  68462. * @param mesh Mesh to add
  68463. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  68464. * @returns the Shadow Generator itself
  68465. */
  68466. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  68467. if (includeDescendants === void 0) { includeDescendants = true; }
  68468. if (!this._shadowMap) {
  68469. return this;
  68470. }
  68471. if (!this._shadowMap.renderList) {
  68472. this._shadowMap.renderList = [];
  68473. }
  68474. this._shadowMap.renderList.push(mesh);
  68475. if (includeDescendants) {
  68476. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  68477. }
  68478. return this;
  68479. var _a;
  68480. };
  68481. /**
  68482. * Helper function to remove a mesh and its descendants from the list of shadow casters
  68483. * @param mesh Mesh to remove
  68484. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  68485. * @returns the Shadow Generator itself
  68486. */
  68487. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  68488. if (includeDescendants === void 0) { includeDescendants = true; }
  68489. if (!this._shadowMap || !this._shadowMap.renderList) {
  68490. return this;
  68491. }
  68492. var index = this._shadowMap.renderList.indexOf(mesh);
  68493. if (index !== -1) {
  68494. this._shadowMap.renderList.splice(index, 1);
  68495. }
  68496. if (includeDescendants) {
  68497. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  68498. var child = _a[_i];
  68499. this.removeShadowCaster(child);
  68500. }
  68501. }
  68502. return this;
  68503. };
  68504. /**
  68505. * Returns the associated light object.
  68506. * @returns the light generating the shadow
  68507. */
  68508. ShadowGenerator.prototype.getLight = function () {
  68509. return this._light;
  68510. };
  68511. ShadowGenerator.prototype._initializeGenerator = function () {
  68512. this._light._markMeshesAsLightDirty();
  68513. this._initializeShadowMap();
  68514. };
  68515. ShadowGenerator.prototype._initializeShadowMap = function () {
  68516. var _this = this;
  68517. // Render target
  68518. var engine = this._scene.getEngine();
  68519. if (engine.webGLVersion > 1) {
  68520. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  68521. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  68522. }
  68523. else {
  68524. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  68525. }
  68526. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68527. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68528. this._shadowMap.anisotropicFilteringLevel = 1;
  68529. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68530. this._shadowMap.renderParticles = false;
  68531. this._shadowMap.ignoreCameraViewport = true;
  68532. // Record Face Index before render.
  68533. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  68534. _this._currentFaceIndex = faceIndex;
  68535. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68536. engine.setColorWrite(false);
  68537. }
  68538. });
  68539. // Custom render function.
  68540. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  68541. // Blur if required afer render.
  68542. this._shadowMap.onAfterUnbindObservable.add(function () {
  68543. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68544. engine.setColorWrite(true);
  68545. }
  68546. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  68547. return;
  68548. }
  68549. var shadowMap = _this.getShadowMapForRendering();
  68550. if (shadowMap) {
  68551. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  68552. }
  68553. });
  68554. // Clear according to the chosen filter.
  68555. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  68556. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  68557. this._shadowMap.onClearObservable.add(function (engine) {
  68558. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68559. engine.clear(clearOne, false, true, false);
  68560. }
  68561. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  68562. engine.clear(clearZero, true, true, false);
  68563. }
  68564. else {
  68565. engine.clear(clearOne, true, true, false);
  68566. }
  68567. });
  68568. };
  68569. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  68570. var _this = this;
  68571. var engine = this._scene.getEngine();
  68572. var targetSize = this._mapSize / this.blurScale;
  68573. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  68574. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  68575. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68576. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68577. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68578. }
  68579. if (this.useKernelBlur) {
  68580. 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);
  68581. this._kernelBlurXPostprocess.width = targetSize;
  68582. this._kernelBlurXPostprocess.height = targetSize;
  68583. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  68584. effect.setTexture("textureSampler", _this._shadowMap);
  68585. });
  68586. 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);
  68587. this._kernelBlurXPostprocess.autoClear = false;
  68588. this._kernelBlurYPostprocess.autoClear = false;
  68589. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68590. this._kernelBlurXPostprocess.packedFloat = true;
  68591. this._kernelBlurYPostprocess.packedFloat = true;
  68592. }
  68593. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  68594. }
  68595. else {
  68596. 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);
  68597. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  68598. effect.setFloat2("screenSize", targetSize, targetSize);
  68599. effect.setTexture("textureSampler", _this._shadowMap);
  68600. });
  68601. this._boxBlurPostprocess.autoClear = false;
  68602. this._blurPostProcesses = [this._boxBlurPostprocess];
  68603. }
  68604. };
  68605. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68606. var index;
  68607. var engine = this._scene.getEngine();
  68608. if (depthOnlySubMeshes.length) {
  68609. engine.setColorWrite(false);
  68610. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68611. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  68612. }
  68613. engine.setColorWrite(true);
  68614. }
  68615. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68616. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68617. }
  68618. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68619. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  68620. }
  68621. if (this._transparencyShadow) {
  68622. for (index = 0; index < transparentSubMeshes.length; index++) {
  68623. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  68624. }
  68625. }
  68626. };
  68627. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  68628. var _this = this;
  68629. var mesh = subMesh.getRenderingMesh();
  68630. var scene = this._scene;
  68631. var engine = scene.getEngine();
  68632. var material = subMesh.getMaterial();
  68633. if (!material) {
  68634. return;
  68635. }
  68636. // Culling
  68637. engine.setState(material.backFaceCulling);
  68638. // Managing instances
  68639. var batch = mesh._getInstancesRenderList(subMesh._id);
  68640. if (batch.mustReturn) {
  68641. return;
  68642. }
  68643. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68644. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  68645. engine.enableEffect(this._effect);
  68646. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68647. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  68648. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  68649. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68650. this._effect.setVector3("lightData", this._cachedDirection);
  68651. }
  68652. else {
  68653. this._effect.setVector3("lightData", this._cachedPosition);
  68654. }
  68655. if (scene.activeCamera) {
  68656. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  68657. }
  68658. // Alpha test
  68659. if (material && material.needAlphaTesting()) {
  68660. var alphaTexture = material.getAlphaTestTexture();
  68661. if (alphaTexture) {
  68662. this._effect.setTexture("diffuseSampler", alphaTexture);
  68663. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  68664. }
  68665. }
  68666. // Bones
  68667. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68668. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  68669. }
  68670. // Morph targets
  68671. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  68672. if (this.forceBackFacesOnly) {
  68673. engine.setState(true, 0, false, true);
  68674. }
  68675. // Draw
  68676. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68677. if (this.forceBackFacesOnly) {
  68678. engine.setState(true, 0, false, false);
  68679. }
  68680. }
  68681. else {
  68682. // Need to reset refresh rate of the shadowMap
  68683. if (this._shadowMap) {
  68684. this._shadowMap.resetRefreshCounter();
  68685. }
  68686. }
  68687. };
  68688. ShadowGenerator.prototype._applyFilterValues = function () {
  68689. if (!this._shadowMap) {
  68690. return;
  68691. }
  68692. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  68693. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68694. }
  68695. else {
  68696. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68697. }
  68698. };
  68699. /**
  68700. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68701. * @param onCompiled Callback triggered at the and of the effects compilation
  68702. * @param options Sets of optional options forcing the compilation with different modes
  68703. */
  68704. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  68705. var _this = this;
  68706. var localOptions = __assign({ useInstances: false }, options);
  68707. var shadowMap = this.getShadowMap();
  68708. if (!shadowMap) {
  68709. if (onCompiled) {
  68710. onCompiled(this);
  68711. }
  68712. return;
  68713. }
  68714. var renderList = shadowMap.renderList;
  68715. if (!renderList) {
  68716. if (onCompiled) {
  68717. onCompiled(this);
  68718. }
  68719. return;
  68720. }
  68721. var subMeshes = new Array();
  68722. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  68723. var mesh = renderList_1[_i];
  68724. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  68725. }
  68726. if (subMeshes.length === 0) {
  68727. if (onCompiled) {
  68728. onCompiled(this);
  68729. }
  68730. return;
  68731. }
  68732. var currentIndex = 0;
  68733. var checkReady = function () {
  68734. if (!_this._scene || !_this._scene.getEngine()) {
  68735. return;
  68736. }
  68737. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  68738. currentIndex++;
  68739. if (currentIndex >= subMeshes.length) {
  68740. if (onCompiled) {
  68741. onCompiled(_this);
  68742. }
  68743. return;
  68744. }
  68745. }
  68746. setTimeout(checkReady, 16);
  68747. };
  68748. checkReady();
  68749. };
  68750. /**
  68751. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68752. * @param options Sets of optional options forcing the compilation with different modes
  68753. * @returns A promise that resolves when the compilation completes
  68754. */
  68755. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  68756. var _this = this;
  68757. return new Promise(function (resolve) {
  68758. _this.forceCompilation(function () {
  68759. resolve();
  68760. }, options);
  68761. });
  68762. };
  68763. /**
  68764. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68765. * @param subMesh The submesh we want to render in the shadow map
  68766. * @param useInstances Defines wether will draw in the map using instances
  68767. * @returns true if ready otherwise, false
  68768. */
  68769. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  68770. var defines = [];
  68771. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68772. defines.push("#define FLOAT");
  68773. }
  68774. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68775. defines.push("#define ESM");
  68776. }
  68777. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  68778. defines.push("#define DEPTHTEXTURE");
  68779. }
  68780. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68781. var mesh = subMesh.getMesh();
  68782. var material = subMesh.getMaterial();
  68783. // Normal bias.
  68784. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68785. attribs.push(BABYLON.VertexBuffer.NormalKind);
  68786. defines.push("#define NORMAL");
  68787. if (mesh.nonUniformScaling) {
  68788. defines.push("#define NONUNIFORMSCALING");
  68789. }
  68790. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68791. defines.push("#define DIRECTIONINLIGHTDATA");
  68792. }
  68793. }
  68794. // Alpha test
  68795. if (material && material.needAlphaTesting()) {
  68796. var alphaTexture = material.getAlphaTestTexture();
  68797. if (alphaTexture) {
  68798. defines.push("#define ALPHATEST");
  68799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68800. attribs.push(BABYLON.VertexBuffer.UVKind);
  68801. defines.push("#define UV1");
  68802. }
  68803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68804. if (alphaTexture.coordinatesIndex === 1) {
  68805. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68806. defines.push("#define UV2");
  68807. }
  68808. }
  68809. }
  68810. }
  68811. // Bones
  68812. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68813. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68814. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68815. if (mesh.numBoneInfluencers > 4) {
  68816. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68817. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68818. }
  68819. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68820. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68821. }
  68822. else {
  68823. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68824. }
  68825. // Morph targets
  68826. var manager = mesh.morphTargetManager;
  68827. var morphInfluencers = 0;
  68828. if (manager) {
  68829. if (manager.numInfluencers > 0) {
  68830. defines.push("#define MORPHTARGETS");
  68831. morphInfluencers = manager.numInfluencers;
  68832. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  68833. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  68834. }
  68835. }
  68836. // Instances
  68837. if (useInstances) {
  68838. defines.push("#define INSTANCES");
  68839. attribs.push("world0");
  68840. attribs.push("world1");
  68841. attribs.push("world2");
  68842. attribs.push("world3");
  68843. }
  68844. // Get correct effect
  68845. var join = defines.join("\n");
  68846. if (this._cachedDefines !== join) {
  68847. this._cachedDefines = join;
  68848. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  68849. }
  68850. if (!this._effect.isReady()) {
  68851. return false;
  68852. }
  68853. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68854. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  68855. this._initializeBlurRTTAndPostProcesses();
  68856. }
  68857. }
  68858. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  68859. return false;
  68860. }
  68861. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  68862. return false;
  68863. }
  68864. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  68865. return false;
  68866. }
  68867. return true;
  68868. };
  68869. /**
  68870. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  68871. * @param defines Defines of the material we want to update
  68872. * @param lightIndex Index of the light in the enabled light list of the material
  68873. */
  68874. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  68875. var scene = this._scene;
  68876. var light = this._light;
  68877. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68878. return;
  68879. }
  68880. defines["SHADOW" + lightIndex] = true;
  68881. if (this.useContactHardeningShadow) {
  68882. defines["SHADOWPCSS" + lightIndex] = true;
  68883. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68884. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68885. }
  68886. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68887. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68888. }
  68889. // else default to high.
  68890. }
  68891. if (this.usePercentageCloserFiltering) {
  68892. defines["SHADOWPCF" + lightIndex] = true;
  68893. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68894. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68895. }
  68896. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68897. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68898. }
  68899. // else default to high.
  68900. }
  68901. else if (this.usePoissonSampling) {
  68902. defines["SHADOWPOISSON" + lightIndex] = true;
  68903. }
  68904. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68905. defines["SHADOWESM" + lightIndex] = true;
  68906. }
  68907. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68908. defines["SHADOWCLOSEESM" + lightIndex] = true;
  68909. }
  68910. if (light.needCube()) {
  68911. defines["SHADOWCUBE" + lightIndex] = true;
  68912. }
  68913. };
  68914. /**
  68915. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  68916. * defined in the generator but impacting the effect).
  68917. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  68918. * @param effect The effect we are binfing the information for
  68919. */
  68920. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  68921. var light = this._light;
  68922. var scene = this._scene;
  68923. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68924. return;
  68925. }
  68926. var camera = scene.activeCamera;
  68927. if (!camera) {
  68928. return;
  68929. }
  68930. var shadowMap = this.getShadowMap();
  68931. if (!shadowMap) {
  68932. return;
  68933. }
  68934. if (!light.needCube()) {
  68935. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  68936. }
  68937. // Only PCF uses depth stencil texture.
  68938. if (this._filter === ShadowGenerator.FILTER_PCF) {
  68939. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68940. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68941. }
  68942. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  68943. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68944. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  68945. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68946. }
  68947. else {
  68948. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68949. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  68950. }
  68951. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  68952. };
  68953. /**
  68954. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  68955. * (eq to shadow prjection matrix * light transform matrix)
  68956. * @returns The transform matrix used to create the shadow map
  68957. */
  68958. ShadowGenerator.prototype.getTransformMatrix = function () {
  68959. var scene = this._scene;
  68960. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  68961. return this._transformMatrix;
  68962. }
  68963. this._currentRenderID = scene.getRenderId();
  68964. this._currentFaceIndexCache = this._currentFaceIndex;
  68965. var lightPosition = this._light.position;
  68966. if (this._light.computeTransformedInformation()) {
  68967. lightPosition = this._light.transformedPosition;
  68968. }
  68969. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  68970. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  68971. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  68972. }
  68973. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  68974. this._cachedPosition.copyFrom(lightPosition);
  68975. this._cachedDirection.copyFrom(this._lightDirection);
  68976. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  68977. var shadowMap = this.getShadowMap();
  68978. if (shadowMap) {
  68979. var renderList = shadowMap.renderList;
  68980. if (renderList) {
  68981. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  68982. }
  68983. }
  68984. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  68985. }
  68986. return this._transformMatrix;
  68987. };
  68988. /**
  68989. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  68990. * Cube and 2D textures for instance.
  68991. */
  68992. ShadowGenerator.prototype.recreateShadowMap = function () {
  68993. var shadowMap = this._shadowMap;
  68994. if (!shadowMap) {
  68995. return;
  68996. }
  68997. // Track render list.
  68998. var renderList = shadowMap.renderList;
  68999. // Clean up existing data.
  69000. this._disposeRTTandPostProcesses();
  69001. // Reinitializes.
  69002. this._initializeGenerator();
  69003. // Reaffect the filter to ensure a correct fallback if necessary.
  69004. this.filter = this.filter;
  69005. // Reaffect the filter.
  69006. this._applyFilterValues();
  69007. // Reaffect Render List.
  69008. this._shadowMap.renderList = renderList;
  69009. };
  69010. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  69011. if (this._shadowMap2) {
  69012. this._shadowMap2.dispose();
  69013. this._shadowMap2 = null;
  69014. }
  69015. if (this._boxBlurPostprocess) {
  69016. this._boxBlurPostprocess.dispose();
  69017. this._boxBlurPostprocess = null;
  69018. }
  69019. if (this._kernelBlurXPostprocess) {
  69020. this._kernelBlurXPostprocess.dispose();
  69021. this._kernelBlurXPostprocess = null;
  69022. }
  69023. if (this._kernelBlurYPostprocess) {
  69024. this._kernelBlurYPostprocess.dispose();
  69025. this._kernelBlurYPostprocess = null;
  69026. }
  69027. this._blurPostProcesses = [];
  69028. };
  69029. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  69030. if (this._shadowMap) {
  69031. this._shadowMap.dispose();
  69032. this._shadowMap = null;
  69033. }
  69034. this._disposeBlurPostProcesses();
  69035. };
  69036. /**
  69037. * Disposes the ShadowGenerator.
  69038. * Returns nothing.
  69039. */
  69040. ShadowGenerator.prototype.dispose = function () {
  69041. this._disposeRTTandPostProcesses();
  69042. if (this._light) {
  69043. this._light._shadowGenerator = null;
  69044. this._light._markMeshesAsLightDirty();
  69045. }
  69046. };
  69047. /**
  69048. * Serializes the shadow generator setup to a json object.
  69049. * @returns The serialized JSON object
  69050. */
  69051. ShadowGenerator.prototype.serialize = function () {
  69052. var serializationObject = {};
  69053. var shadowMap = this.getShadowMap();
  69054. if (!shadowMap) {
  69055. return serializationObject;
  69056. }
  69057. serializationObject.lightId = this._light.id;
  69058. serializationObject.mapSize = shadowMap.getRenderSize();
  69059. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  69060. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  69061. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69062. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69063. serializationObject.usePoissonSampling = this.usePoissonSampling;
  69064. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  69065. serializationObject.depthScale = this.depthScale;
  69066. serializationObject.darkness = this.getDarkness();
  69067. serializationObject.blurBoxOffset = this.blurBoxOffset;
  69068. serializationObject.blurKernel = this.blurKernel;
  69069. serializationObject.blurScale = this.blurScale;
  69070. serializationObject.useKernelBlur = this.useKernelBlur;
  69071. serializationObject.transparencyShadow = this._transparencyShadow;
  69072. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  69073. serializationObject.bias = this.bias;
  69074. serializationObject.normalBias = this.normalBias;
  69075. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  69076. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  69077. serializationObject.filteringQuality = this.filteringQuality;
  69078. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  69079. serializationObject.renderList = [];
  69080. if (shadowMap.renderList) {
  69081. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  69082. var mesh = shadowMap.renderList[meshIndex];
  69083. serializationObject.renderList.push(mesh.id);
  69084. }
  69085. }
  69086. return serializationObject;
  69087. };
  69088. /**
  69089. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  69090. * @param parsedShadowGenerator The JSON object to parse
  69091. * @param scene The scene to create the shadow map for
  69092. * @returns The parsed shadow generator
  69093. */
  69094. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  69095. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  69096. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  69097. var shadowMap = shadowGenerator.getShadowMap();
  69098. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  69099. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  69100. meshes.forEach(function (mesh) {
  69101. if (!shadowMap) {
  69102. return;
  69103. }
  69104. if (!shadowMap.renderList) {
  69105. shadowMap.renderList = [];
  69106. }
  69107. shadowMap.renderList.push(mesh);
  69108. });
  69109. }
  69110. if (parsedShadowGenerator.usePoissonSampling) {
  69111. shadowGenerator.usePoissonSampling = true;
  69112. }
  69113. else if (parsedShadowGenerator.useExponentialShadowMap) {
  69114. shadowGenerator.useExponentialShadowMap = true;
  69115. }
  69116. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  69117. shadowGenerator.useBlurExponentialShadowMap = true;
  69118. }
  69119. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  69120. shadowGenerator.useCloseExponentialShadowMap = true;
  69121. }
  69122. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  69123. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  69124. }
  69125. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  69126. shadowGenerator.usePercentageCloserFiltering = true;
  69127. }
  69128. else if (parsedShadowGenerator.useContactHardeningShadow) {
  69129. shadowGenerator.useContactHardeningShadow = true;
  69130. }
  69131. if (parsedShadowGenerator.filteringQuality) {
  69132. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  69133. }
  69134. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  69135. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  69136. }
  69137. // Backward compat
  69138. else if (parsedShadowGenerator.useVarianceShadowMap) {
  69139. shadowGenerator.useExponentialShadowMap = true;
  69140. }
  69141. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  69142. shadowGenerator.useBlurExponentialShadowMap = true;
  69143. }
  69144. if (parsedShadowGenerator.depthScale) {
  69145. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  69146. }
  69147. if (parsedShadowGenerator.blurScale) {
  69148. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  69149. }
  69150. if (parsedShadowGenerator.blurBoxOffset) {
  69151. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  69152. }
  69153. if (parsedShadowGenerator.useKernelBlur) {
  69154. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  69155. }
  69156. if (parsedShadowGenerator.blurKernel) {
  69157. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  69158. }
  69159. if (parsedShadowGenerator.bias !== undefined) {
  69160. shadowGenerator.bias = parsedShadowGenerator.bias;
  69161. }
  69162. if (parsedShadowGenerator.normalBias !== undefined) {
  69163. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  69164. }
  69165. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  69166. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  69167. }
  69168. if (parsedShadowGenerator.darkness) {
  69169. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  69170. }
  69171. if (parsedShadowGenerator.transparencyShadow) {
  69172. shadowGenerator.setTransparencyShadow(true);
  69173. }
  69174. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  69175. return shadowGenerator;
  69176. };
  69177. /**
  69178. * Shadow generator mode None: no filtering applied.
  69179. */
  69180. ShadowGenerator.FILTER_NONE = 0;
  69181. /**
  69182. * Shadow generator mode ESM: Exponential Shadow Mapping.
  69183. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69184. */
  69185. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  69186. /**
  69187. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  69188. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  69189. */
  69190. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  69191. /**
  69192. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  69193. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69194. */
  69195. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  69196. /**
  69197. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  69198. * edge artifacts on steep falloff.
  69199. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69200. */
  69201. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  69202. /**
  69203. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  69204. * edge artifacts on steep falloff.
  69205. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69206. */
  69207. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  69208. /**
  69209. * Shadow generator mode PCF: Percentage Closer Filtering
  69210. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69211. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  69212. */
  69213. ShadowGenerator.FILTER_PCF = 6;
  69214. /**
  69215. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  69216. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69217. * Contact Hardening
  69218. */
  69219. ShadowGenerator.FILTER_PCSS = 7;
  69220. /**
  69221. * Reserved for PCF and PCSS
  69222. * Highest Quality.
  69223. *
  69224. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  69225. *
  69226. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  69227. */
  69228. ShadowGenerator.QUALITY_HIGH = 0;
  69229. /**
  69230. * Reserved for PCF and PCSS
  69231. * Good tradeoff for quality/perf cross devices
  69232. *
  69233. * Execute PCF on a 3*3 kernel.
  69234. *
  69235. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  69236. */
  69237. ShadowGenerator.QUALITY_MEDIUM = 1;
  69238. /**
  69239. * Reserved for PCF and PCSS
  69240. * The lowest quality but the fastest.
  69241. *
  69242. * Execute PCF on a 1*1 kernel.
  69243. *
  69244. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  69245. */
  69246. ShadowGenerator.QUALITY_LOW = 2;
  69247. return ShadowGenerator;
  69248. }());
  69249. BABYLON.ShadowGenerator = ShadowGenerator;
  69250. })(BABYLON || (BABYLON = {}));
  69251. //# sourceMappingURL=babylon.shadowGenerator.js.map
  69252. var BABYLON;
  69253. (function (BABYLON) {
  69254. var DefaultLoadingScreen = /** @class */ (function () {
  69255. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  69256. if (_loadingText === void 0) { _loadingText = ""; }
  69257. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  69258. var _this = this;
  69259. this._renderingCanvas = _renderingCanvas;
  69260. this._loadingText = _loadingText;
  69261. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  69262. // Resize
  69263. this._resizeLoadingUI = function () {
  69264. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  69265. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  69266. if (!_this._loadingDiv) {
  69267. return;
  69268. }
  69269. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  69270. _this._loadingDiv.style.left = canvasRect.left + "px";
  69271. _this._loadingDiv.style.top = canvasRect.top + "px";
  69272. _this._loadingDiv.style.width = canvasRect.width + "px";
  69273. _this._loadingDiv.style.height = canvasRect.height + "px";
  69274. };
  69275. }
  69276. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  69277. if (this._loadingDiv) {
  69278. // Do not add a loading screen if there is already one
  69279. return;
  69280. }
  69281. this._loadingDiv = document.createElement("div");
  69282. this._loadingDiv.id = "babylonjsLoadingDiv";
  69283. this._loadingDiv.style.opacity = "0";
  69284. this._loadingDiv.style.transition = "opacity 1.5s ease";
  69285. this._loadingDiv.style.pointerEvents = "none";
  69286. // Loading text
  69287. this._loadingTextDiv = document.createElement("div");
  69288. this._loadingTextDiv.style.position = "absolute";
  69289. this._loadingTextDiv.style.left = "0";
  69290. this._loadingTextDiv.style.top = "50%";
  69291. this._loadingTextDiv.style.marginTop = "80px";
  69292. this._loadingTextDiv.style.width = "100%";
  69293. this._loadingTextDiv.style.height = "20px";
  69294. this._loadingTextDiv.style.fontFamily = "Arial";
  69295. this._loadingTextDiv.style.fontSize = "14px";
  69296. this._loadingTextDiv.style.color = "white";
  69297. this._loadingTextDiv.style.textAlign = "center";
  69298. this._loadingTextDiv.innerHTML = "Loading";
  69299. this._loadingDiv.appendChild(this._loadingTextDiv);
  69300. //set the predefined text
  69301. this._loadingTextDiv.innerHTML = this._loadingText;
  69302. // Generating keyframes
  69303. var style = document.createElement('style');
  69304. style.type = 'text/css';
  69305. 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 }";
  69306. style.innerHTML = keyFrames;
  69307. document.getElementsByTagName('head')[0].appendChild(style);
  69308. // Loading img
  69309. var imgBack = new Image();
  69310. 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";
  69311. imgBack.style.position = "absolute";
  69312. imgBack.style.left = "50%";
  69313. imgBack.style.top = "50%";
  69314. imgBack.style.marginLeft = "-60px";
  69315. imgBack.style.marginTop = "-60px";
  69316. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  69317. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  69318. imgBack.style.transformOrigin = "50% 50%";
  69319. imgBack.style.webkitTransformOrigin = "50% 50%";
  69320. this._loadingDiv.appendChild(imgBack);
  69321. this._resizeLoadingUI();
  69322. window.addEventListener("resize", this._resizeLoadingUI);
  69323. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69324. document.body.appendChild(this._loadingDiv);
  69325. this._loadingDiv.style.opacity = "1";
  69326. };
  69327. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  69328. var _this = this;
  69329. if (!this._loadingDiv) {
  69330. return;
  69331. }
  69332. var onTransitionEnd = function () {
  69333. if (!_this._loadingDiv) {
  69334. return;
  69335. }
  69336. document.body.removeChild(_this._loadingDiv);
  69337. window.removeEventListener("resize", _this._resizeLoadingUI);
  69338. _this._loadingDiv = null;
  69339. };
  69340. this._loadingDiv.style.opacity = "0";
  69341. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  69342. };
  69343. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  69344. set: function (text) {
  69345. this._loadingText = text;
  69346. if (this._loadingTextDiv) {
  69347. this._loadingTextDiv.innerHTML = this._loadingText;
  69348. }
  69349. },
  69350. enumerable: true,
  69351. configurable: true
  69352. });
  69353. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  69354. get: function () {
  69355. return this._loadingDivBackgroundColor;
  69356. },
  69357. set: function (color) {
  69358. this._loadingDivBackgroundColor = color;
  69359. if (!this._loadingDiv) {
  69360. return;
  69361. }
  69362. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69363. },
  69364. enumerable: true,
  69365. configurable: true
  69366. });
  69367. return DefaultLoadingScreen;
  69368. }());
  69369. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  69370. })(BABYLON || (BABYLON = {}));
  69371. //# sourceMappingURL=babylon.loadingScreen.js.map
  69372. var BABYLON;
  69373. (function (BABYLON) {
  69374. var SceneLoaderProgressEvent = /** @class */ (function () {
  69375. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  69376. this.lengthComputable = lengthComputable;
  69377. this.loaded = loaded;
  69378. this.total = total;
  69379. }
  69380. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  69381. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  69382. };
  69383. return SceneLoaderProgressEvent;
  69384. }());
  69385. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  69386. var SceneLoader = /** @class */ (function () {
  69387. function SceneLoader() {
  69388. }
  69389. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  69390. get: function () {
  69391. return 0;
  69392. },
  69393. enumerable: true,
  69394. configurable: true
  69395. });
  69396. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  69397. get: function () {
  69398. return 1;
  69399. },
  69400. enumerable: true,
  69401. configurable: true
  69402. });
  69403. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  69404. get: function () {
  69405. return 2;
  69406. },
  69407. enumerable: true,
  69408. configurable: true
  69409. });
  69410. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  69411. get: function () {
  69412. return 3;
  69413. },
  69414. enumerable: true,
  69415. configurable: true
  69416. });
  69417. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  69418. get: function () {
  69419. return SceneLoader._ForceFullSceneLoadingForIncremental;
  69420. },
  69421. set: function (value) {
  69422. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  69423. },
  69424. enumerable: true,
  69425. configurable: true
  69426. });
  69427. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  69428. get: function () {
  69429. return SceneLoader._ShowLoadingScreen;
  69430. },
  69431. set: function (value) {
  69432. SceneLoader._ShowLoadingScreen = value;
  69433. },
  69434. enumerable: true,
  69435. configurable: true
  69436. });
  69437. Object.defineProperty(SceneLoader, "loggingLevel", {
  69438. get: function () {
  69439. return SceneLoader._loggingLevel;
  69440. },
  69441. set: function (value) {
  69442. SceneLoader._loggingLevel = value;
  69443. },
  69444. enumerable: true,
  69445. configurable: true
  69446. });
  69447. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  69448. get: function () {
  69449. return SceneLoader._CleanBoneMatrixWeights;
  69450. },
  69451. set: function (value) {
  69452. SceneLoader._CleanBoneMatrixWeights = value;
  69453. },
  69454. enumerable: true,
  69455. configurable: true
  69456. });
  69457. SceneLoader._getDefaultPlugin = function () {
  69458. return SceneLoader._registeredPlugins[".babylon"];
  69459. };
  69460. SceneLoader._getPluginForExtension = function (extension) {
  69461. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  69462. if (registeredPlugin) {
  69463. return registeredPlugin;
  69464. }
  69465. 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");
  69466. return SceneLoader._getDefaultPlugin();
  69467. };
  69468. SceneLoader._getPluginForDirectLoad = function (data) {
  69469. for (var extension in SceneLoader._registeredPlugins) {
  69470. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  69471. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  69472. return SceneLoader._registeredPlugins[extension];
  69473. }
  69474. }
  69475. return SceneLoader._getDefaultPlugin();
  69476. };
  69477. SceneLoader._getPluginForFilename = function (sceneFilename) {
  69478. if (sceneFilename.name) {
  69479. sceneFilename = sceneFilename.name;
  69480. }
  69481. var queryStringPosition = sceneFilename.indexOf("?");
  69482. if (queryStringPosition !== -1) {
  69483. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  69484. }
  69485. var dotPosition = sceneFilename.lastIndexOf(".");
  69486. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  69487. return SceneLoader._getPluginForExtension(extension);
  69488. };
  69489. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  69490. SceneLoader._getDirectLoad = function (sceneFilename) {
  69491. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  69492. return sceneFilename.substr(5);
  69493. }
  69494. return null;
  69495. };
  69496. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  69497. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  69498. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  69499. var plugin;
  69500. if (registeredPlugin.plugin.createPlugin) {
  69501. plugin = registeredPlugin.plugin.createPlugin();
  69502. }
  69503. else {
  69504. plugin = registeredPlugin.plugin;
  69505. }
  69506. var useArrayBuffer = registeredPlugin.isBinary;
  69507. var database;
  69508. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  69509. var dataCallback = function (data, responseURL) {
  69510. if (scene.isDisposed) {
  69511. onError("Scene has been disposed");
  69512. return;
  69513. }
  69514. scene.database = database;
  69515. onSuccess(plugin, data, responseURL);
  69516. };
  69517. var request = null;
  69518. var pluginDisposed = false;
  69519. var onDisposeObservable = plugin.onDisposeObservable;
  69520. if (onDisposeObservable) {
  69521. onDisposeObservable.add(function () {
  69522. pluginDisposed = true;
  69523. if (request) {
  69524. request.abort();
  69525. request = null;
  69526. }
  69527. onDispose();
  69528. });
  69529. }
  69530. var manifestChecked = function () {
  69531. if (pluginDisposed) {
  69532. return;
  69533. }
  69534. var url = rootUrl + sceneFilename;
  69535. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  69536. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  69537. } : undefined, database, useArrayBuffer, function (request, exception) {
  69538. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  69539. });
  69540. };
  69541. if (directLoad) {
  69542. dataCallback(directLoad);
  69543. return plugin;
  69544. }
  69545. if (rootUrl.indexOf("file:") === -1) {
  69546. var engine = scene.getEngine();
  69547. var canUseOfflineSupport = engine.enableOfflineSupport;
  69548. if (canUseOfflineSupport) {
  69549. // Also check for exceptions
  69550. var exceptionFound = false;
  69551. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  69552. var regex = _a[_i];
  69553. if (regex.test(rootUrl + sceneFilename)) {
  69554. exceptionFound = true;
  69555. break;
  69556. }
  69557. }
  69558. canUseOfflineSupport = !exceptionFound;
  69559. }
  69560. if (canUseOfflineSupport) {
  69561. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  69562. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  69563. }
  69564. else {
  69565. manifestChecked();
  69566. }
  69567. }
  69568. // Loading file from disk via input file or drag'n'drop
  69569. else {
  69570. var fileOrString = sceneFilename;
  69571. if (fileOrString.name) { // File
  69572. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  69573. }
  69574. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  69575. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  69576. }
  69577. else {
  69578. onError("Unable to find file named " + sceneFilename);
  69579. }
  69580. }
  69581. return plugin;
  69582. };
  69583. // Public functions
  69584. SceneLoader.GetPluginForExtension = function (extension) {
  69585. return SceneLoader._getPluginForExtension(extension).plugin;
  69586. };
  69587. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  69588. return !!SceneLoader._registeredPlugins[extension];
  69589. };
  69590. SceneLoader.RegisterPlugin = function (plugin) {
  69591. if (typeof plugin.extensions === "string") {
  69592. var extension = plugin.extensions;
  69593. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69594. plugin: plugin,
  69595. isBinary: false
  69596. };
  69597. }
  69598. else {
  69599. var extensions = plugin.extensions;
  69600. Object.keys(extensions).forEach(function (extension) {
  69601. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69602. plugin: plugin,
  69603. isBinary: extensions[extension].isBinary
  69604. };
  69605. });
  69606. }
  69607. };
  69608. /**
  69609. * Import meshes into a scene
  69610. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69611. * @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)
  69612. * @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)
  69613. * @param scene the instance of BABYLON.Scene to append to
  69614. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69615. * @param onProgress a callback with a progress event for each file being loaded
  69616. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69617. * @param pluginExtension the extension used to determine the plugin
  69618. * @returns The loaded plugin
  69619. */
  69620. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69621. if (sceneFilename === void 0) { sceneFilename = ""; }
  69622. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69623. if (onSuccess === void 0) { onSuccess = null; }
  69624. if (onProgress === void 0) { onProgress = null; }
  69625. if (onError === void 0) { onError = null; }
  69626. if (pluginExtension === void 0) { pluginExtension = null; }
  69627. if (!scene) {
  69628. BABYLON.Tools.Error("No scene available to import mesh to");
  69629. return null;
  69630. }
  69631. if (!sceneFilename) {
  69632. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69633. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69634. }
  69635. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69636. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69637. return null;
  69638. }
  69639. var loadingToken = {};
  69640. scene._addPendingData(loadingToken);
  69641. var disposeHandler = function () {
  69642. scene._removePendingData(loadingToken);
  69643. };
  69644. var errorHandler = function (message, exception) {
  69645. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  69646. if (onError) {
  69647. onError(scene, errorMessage, exception);
  69648. }
  69649. else {
  69650. BABYLON.Tools.Error(errorMessage);
  69651. // should the exception be thrown?
  69652. }
  69653. disposeHandler();
  69654. };
  69655. var progressHandler = onProgress ? function (event) {
  69656. try {
  69657. onProgress(event);
  69658. }
  69659. catch (e) {
  69660. errorHandler("Error in onProgress callback", e);
  69661. }
  69662. } : undefined;
  69663. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  69664. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  69665. if (onSuccess) {
  69666. try {
  69667. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  69668. }
  69669. catch (e) {
  69670. errorHandler("Error in onSuccess callback", e);
  69671. }
  69672. }
  69673. scene._removePendingData(loadingToken);
  69674. };
  69675. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69676. if (plugin.rewriteRootURL) {
  69677. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  69678. }
  69679. if (sceneFilename === "") {
  69680. if (sceneFilename === "") {
  69681. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69682. }
  69683. }
  69684. if (plugin.importMesh) {
  69685. var syncedPlugin = plugin;
  69686. var meshes = new Array();
  69687. var particleSystems = new Array();
  69688. var skeletons = new Array();
  69689. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  69690. return;
  69691. }
  69692. scene.loadingPluginName = plugin.name;
  69693. successHandler(meshes, particleSystems, skeletons, []);
  69694. }
  69695. else {
  69696. var asyncedPlugin = plugin;
  69697. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  69698. scene.loadingPluginName = plugin.name;
  69699. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  69700. }).catch(function (error) {
  69701. errorHandler(error.message, error);
  69702. });
  69703. }
  69704. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69705. };
  69706. /**
  69707. * Import meshes into a scene
  69708. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69709. * @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)
  69710. * @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)
  69711. * @param scene the instance of BABYLON.Scene to append to
  69712. * @param onProgress a callback with a progress event for each file being loaded
  69713. * @param pluginExtension the extension used to determine the plugin
  69714. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  69715. */
  69716. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69717. if (sceneFilename === void 0) { sceneFilename = ""; }
  69718. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69719. if (onProgress === void 0) { onProgress = null; }
  69720. if (pluginExtension === void 0) { pluginExtension = null; }
  69721. return new Promise(function (resolve, reject) {
  69722. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  69723. resolve({
  69724. meshes: meshes,
  69725. particleSystems: particleSystems,
  69726. skeletons: skeletons,
  69727. animationGroups: animationGroups
  69728. });
  69729. }, onProgress, function (scene, message, exception) {
  69730. reject(exception || new Error(message));
  69731. }, pluginExtension);
  69732. });
  69733. };
  69734. /**
  69735. * Load a scene
  69736. * @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)
  69737. * @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)
  69738. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69739. * @param onSuccess a callback with the scene when import succeeds
  69740. * @param onProgress a callback with a progress event for each file being loaded
  69741. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69742. * @param pluginExtension the extension used to determine the plugin
  69743. * @returns The loaded plugin
  69744. */
  69745. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  69746. if (onSuccess === void 0) { onSuccess = null; }
  69747. if (onProgress === void 0) { onProgress = null; }
  69748. if (onError === void 0) { onError = null; }
  69749. if (pluginExtension === void 0) { pluginExtension = null; }
  69750. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  69751. };
  69752. /**
  69753. * Load a scene
  69754. * @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)
  69755. * @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)
  69756. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69757. * @param onProgress a callback with a progress event for each file being loaded
  69758. * @param pluginExtension the extension used to determine the plugin
  69759. * @returns The loaded scene
  69760. */
  69761. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  69762. if (onProgress === void 0) { onProgress = null; }
  69763. if (pluginExtension === void 0) { pluginExtension = null; }
  69764. return new Promise(function (resolve, reject) {
  69765. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  69766. resolve(scene);
  69767. }, onProgress, function (scene, message, exception) {
  69768. reject(exception || new Error(message));
  69769. }, pluginExtension);
  69770. });
  69771. };
  69772. /**
  69773. * Append a scene
  69774. * @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)
  69775. * @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)
  69776. * @param scene is the instance of BABYLON.Scene to append to
  69777. * @param onSuccess a callback with the scene when import succeeds
  69778. * @param onProgress a callback with a progress event for each file being loaded
  69779. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69780. * @param pluginExtension the extension used to determine the plugin
  69781. * @returns The loaded plugin
  69782. */
  69783. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69784. if (sceneFilename === void 0) { sceneFilename = ""; }
  69785. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69786. if (onSuccess === void 0) { onSuccess = null; }
  69787. if (onProgress === void 0) { onProgress = null; }
  69788. if (onError === void 0) { onError = null; }
  69789. if (pluginExtension === void 0) { pluginExtension = null; }
  69790. if (!scene) {
  69791. BABYLON.Tools.Error("No scene available to append to");
  69792. return null;
  69793. }
  69794. if (!sceneFilename) {
  69795. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69796. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69797. }
  69798. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69799. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69800. return null;
  69801. }
  69802. if (SceneLoader.ShowLoadingScreen) {
  69803. scene.getEngine().displayLoadingUI();
  69804. }
  69805. var loadingToken = {};
  69806. scene._addPendingData(loadingToken);
  69807. var disposeHandler = function () {
  69808. scene._removePendingData(loadingToken);
  69809. scene.getEngine().hideLoadingUI();
  69810. };
  69811. var errorHandler = function (message, exception) {
  69812. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69813. if (onError) {
  69814. onError(scene, errorMessage, exception);
  69815. }
  69816. else {
  69817. BABYLON.Tools.Error(errorMessage);
  69818. // should the exception be thrown?
  69819. }
  69820. disposeHandler();
  69821. };
  69822. var progressHandler = onProgress ? function (event) {
  69823. try {
  69824. onProgress(event);
  69825. }
  69826. catch (e) {
  69827. errorHandler("Error in onProgress callback", e);
  69828. }
  69829. } : undefined;
  69830. var successHandler = function () {
  69831. if (onSuccess) {
  69832. try {
  69833. onSuccess(scene);
  69834. }
  69835. catch (e) {
  69836. errorHandler("Error in onSuccess callback", e);
  69837. }
  69838. }
  69839. scene._removePendingData(loadingToken);
  69840. };
  69841. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69842. if (sceneFilename === "") {
  69843. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69844. }
  69845. if (plugin.load) {
  69846. var syncedPlugin = plugin;
  69847. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  69848. return;
  69849. }
  69850. scene.loadingPluginName = plugin.name;
  69851. successHandler();
  69852. }
  69853. else {
  69854. var asyncedPlugin = plugin;
  69855. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  69856. scene.loadingPluginName = plugin.name;
  69857. successHandler();
  69858. }).catch(function (error) {
  69859. errorHandler(error.message, error);
  69860. });
  69861. }
  69862. if (SceneLoader.ShowLoadingScreen) {
  69863. scene.executeWhenReady(function () {
  69864. scene.getEngine().hideLoadingUI();
  69865. });
  69866. }
  69867. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69868. };
  69869. /**
  69870. * Append a scene
  69871. * @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)
  69872. * @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)
  69873. * @param scene is the instance of BABYLON.Scene to append to
  69874. * @param onProgress a callback with a progress event for each file being loaded
  69875. * @param pluginExtension the extension used to determine the plugin
  69876. * @returns The given scene
  69877. */
  69878. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69879. if (sceneFilename === void 0) { sceneFilename = ""; }
  69880. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69881. if (onProgress === void 0) { onProgress = null; }
  69882. if (pluginExtension === void 0) { pluginExtension = null; }
  69883. return new Promise(function (resolve, reject) {
  69884. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  69885. resolve(scene);
  69886. }, onProgress, function (scene, message, exception) {
  69887. reject(exception || new Error(message));
  69888. }, pluginExtension);
  69889. });
  69890. };
  69891. /**
  69892. * Load a scene into an asset container
  69893. * @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)
  69894. * @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)
  69895. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  69896. * @param onSuccess a callback with the scene when import succeeds
  69897. * @param onProgress a callback with a progress event for each file being loaded
  69898. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69899. * @param pluginExtension the extension used to determine the plugin
  69900. * @returns The loaded plugin
  69901. */
  69902. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69903. if (sceneFilename === void 0) { sceneFilename = ""; }
  69904. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69905. if (onSuccess === void 0) { onSuccess = null; }
  69906. if (onProgress === void 0) { onProgress = null; }
  69907. if (onError === void 0) { onError = null; }
  69908. if (pluginExtension === void 0) { pluginExtension = null; }
  69909. if (!scene) {
  69910. BABYLON.Tools.Error("No scene available to load asset container to");
  69911. return null;
  69912. }
  69913. if (!sceneFilename) {
  69914. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69915. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69916. }
  69917. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69918. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69919. return null;
  69920. }
  69921. var loadingToken = {};
  69922. scene._addPendingData(loadingToken);
  69923. var disposeHandler = function () {
  69924. scene._removePendingData(loadingToken);
  69925. };
  69926. var errorHandler = function (message, exception) {
  69927. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69928. if (onError) {
  69929. onError(scene, errorMessage, exception);
  69930. }
  69931. else {
  69932. BABYLON.Tools.Error(errorMessage);
  69933. // should the exception be thrown?
  69934. }
  69935. disposeHandler();
  69936. };
  69937. var progressHandler = onProgress ? function (event) {
  69938. try {
  69939. onProgress(event);
  69940. }
  69941. catch (e) {
  69942. errorHandler("Error in onProgress callback", e);
  69943. }
  69944. } : undefined;
  69945. var successHandler = function (assets) {
  69946. if (onSuccess) {
  69947. try {
  69948. onSuccess(assets);
  69949. }
  69950. catch (e) {
  69951. errorHandler("Error in onSuccess callback", e);
  69952. }
  69953. }
  69954. scene._removePendingData(loadingToken);
  69955. };
  69956. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69957. if (plugin.loadAssetContainer) {
  69958. var syncedPlugin = plugin;
  69959. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  69960. if (!assetContainer) {
  69961. return;
  69962. }
  69963. scene.loadingPluginName = plugin.name;
  69964. successHandler(assetContainer);
  69965. }
  69966. else if (plugin.loadAssetContainerAsync) {
  69967. var asyncedPlugin = plugin;
  69968. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  69969. scene.loadingPluginName = plugin.name;
  69970. successHandler(assetContainer);
  69971. }).catch(function (error) {
  69972. errorHandler(error.message, error);
  69973. });
  69974. }
  69975. else {
  69976. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  69977. }
  69978. if (SceneLoader.ShowLoadingScreen) {
  69979. scene.executeWhenReady(function () {
  69980. scene.getEngine().hideLoadingUI();
  69981. });
  69982. }
  69983. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69984. };
  69985. /**
  69986. * Load a scene into an asset container
  69987. * @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)
  69988. * @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)
  69989. * @param scene is the instance of BABYLON.Scene to append to
  69990. * @param onProgress a callback with a progress event for each file being loaded
  69991. * @param pluginExtension the extension used to determine the plugin
  69992. * @returns The loaded asset container
  69993. */
  69994. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69995. if (sceneFilename === void 0) { sceneFilename = ""; }
  69996. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69997. if (onProgress === void 0) { onProgress = null; }
  69998. if (pluginExtension === void 0) { pluginExtension = null; }
  69999. return new Promise(function (resolve, reject) {
  70000. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  70001. resolve(assetContainer);
  70002. }, onProgress, function (scene, message, exception) {
  70003. reject(exception || new Error(message));
  70004. }, pluginExtension);
  70005. });
  70006. };
  70007. // Flags
  70008. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  70009. SceneLoader._ShowLoadingScreen = true;
  70010. SceneLoader._CleanBoneMatrixWeights = false;
  70011. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  70012. // Members
  70013. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  70014. SceneLoader._registeredPlugins = {};
  70015. return SceneLoader;
  70016. }());
  70017. BABYLON.SceneLoader = SceneLoader;
  70018. ;
  70019. })(BABYLON || (BABYLON = {}));
  70020. //# sourceMappingURL=babylon.sceneLoader.js.map
  70021. var BABYLON;
  70022. (function (BABYLON) {
  70023. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  70024. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70025. var parsedMaterial = parsedData.materials[index];
  70026. if (parsedMaterial.id === id) {
  70027. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70028. }
  70029. }
  70030. return null;
  70031. };
  70032. var isDescendantOf = function (mesh, names, hierarchyIds) {
  70033. for (var i in names) {
  70034. if (mesh.name === names[i]) {
  70035. hierarchyIds.push(mesh.id);
  70036. return true;
  70037. }
  70038. }
  70039. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  70040. hierarchyIds.push(mesh.id);
  70041. return true;
  70042. }
  70043. return false;
  70044. };
  70045. var logOperation = function (operation, producer) {
  70046. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  70047. };
  70048. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  70049. if (addToScene === void 0) { addToScene = false; }
  70050. var container = new BABYLON.AssetContainer(scene);
  70051. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70052. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70053. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70054. // and avoid problems with multiple concurrent .babylon loads.
  70055. var log = "importScene has failed JSON parse";
  70056. try {
  70057. var parsedData = JSON.parse(data);
  70058. log = "";
  70059. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70060. var index;
  70061. var cache;
  70062. // Lights
  70063. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  70064. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  70065. var parsedLight = parsedData.lights[index];
  70066. var light = BABYLON.Light.Parse(parsedLight, scene);
  70067. if (light) {
  70068. container.lights.push(light);
  70069. log += (index === 0 ? "\n\tLights:" : "");
  70070. log += "\n\t\t" + light.toString(fullDetails);
  70071. }
  70072. }
  70073. }
  70074. // Animations
  70075. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  70076. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  70077. var parsedAnimation = parsedData.animations[index];
  70078. var animation = BABYLON.Animation.Parse(parsedAnimation);
  70079. scene.animations.push(animation);
  70080. container.animations.push(animation);
  70081. log += (index === 0 ? "\n\tAnimations:" : "");
  70082. log += "\n\t\t" + animation.toString(fullDetails);
  70083. }
  70084. }
  70085. // Materials
  70086. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  70087. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70088. var parsedMaterial = parsedData.materials[index];
  70089. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70090. container.materials.push(mat);
  70091. log += (index === 0 ? "\n\tMaterials:" : "");
  70092. log += "\n\t\t" + mat.toString(fullDetails);
  70093. }
  70094. }
  70095. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70096. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  70097. var parsedMultiMaterial = parsedData.multiMaterials[index];
  70098. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70099. container.multiMaterials.push(mmat);
  70100. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  70101. log += "\n\t\t" + mmat.toString(fullDetails);
  70102. }
  70103. }
  70104. // Morph targets
  70105. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70106. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70107. var managerData = _a[_i];
  70108. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  70109. }
  70110. }
  70111. // Skeletons
  70112. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70113. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  70114. var parsedSkeleton = parsedData.skeletons[index];
  70115. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70116. container.skeletons.push(skeleton);
  70117. log += (index === 0 ? "\n\tSkeletons:" : "");
  70118. log += "\n\t\t" + skeleton.toString(fullDetails);
  70119. }
  70120. }
  70121. // Geometries
  70122. var geometries = parsedData.geometries;
  70123. if (geometries !== undefined && geometries !== null) {
  70124. var addedGeometry = new Array();
  70125. // Boxes
  70126. var boxes = geometries.boxes;
  70127. if (boxes !== undefined && boxes !== null) {
  70128. for (index = 0, cache = boxes.length; index < cache; index++) {
  70129. var parsedBox = boxes[index];
  70130. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  70131. }
  70132. }
  70133. // Spheres
  70134. var spheres = geometries.spheres;
  70135. if (spheres !== undefined && spheres !== null) {
  70136. for (index = 0, cache = spheres.length; index < cache; index++) {
  70137. var parsedSphere = spheres[index];
  70138. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  70139. }
  70140. }
  70141. // Cylinders
  70142. var cylinders = geometries.cylinders;
  70143. if (cylinders !== undefined && cylinders !== null) {
  70144. for (index = 0, cache = cylinders.length; index < cache; index++) {
  70145. var parsedCylinder = cylinders[index];
  70146. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  70147. }
  70148. }
  70149. // Toruses
  70150. var toruses = geometries.toruses;
  70151. if (toruses !== undefined && toruses !== null) {
  70152. for (index = 0, cache = toruses.length; index < cache; index++) {
  70153. var parsedTorus = toruses[index];
  70154. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  70155. }
  70156. }
  70157. // Grounds
  70158. var grounds = geometries.grounds;
  70159. if (grounds !== undefined && grounds !== null) {
  70160. for (index = 0, cache = grounds.length; index < cache; index++) {
  70161. var parsedGround = grounds[index];
  70162. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  70163. }
  70164. }
  70165. // Planes
  70166. var planes = geometries.planes;
  70167. if (planes !== undefined && planes !== null) {
  70168. for (index = 0, cache = planes.length; index < cache; index++) {
  70169. var parsedPlane = planes[index];
  70170. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  70171. }
  70172. }
  70173. // TorusKnots
  70174. var torusKnots = geometries.torusKnots;
  70175. if (torusKnots !== undefined && torusKnots !== null) {
  70176. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  70177. var parsedTorusKnot = torusKnots[index];
  70178. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  70179. }
  70180. }
  70181. // VertexData
  70182. var vertexData = geometries.vertexData;
  70183. if (vertexData !== undefined && vertexData !== null) {
  70184. for (index = 0, cache = vertexData.length; index < cache; index++) {
  70185. var parsedVertexData = vertexData[index];
  70186. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  70187. }
  70188. }
  70189. addedGeometry.forEach(function (g) {
  70190. if (g) {
  70191. container.geometries.push(g);
  70192. }
  70193. });
  70194. }
  70195. // Transform nodes
  70196. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  70197. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  70198. var parsedTransformNode = parsedData.transformNodes[index];
  70199. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  70200. container.transformNodes.push(node);
  70201. }
  70202. }
  70203. // Meshes
  70204. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70205. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70206. var parsedMesh = parsedData.meshes[index];
  70207. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70208. container.meshes.push(mesh);
  70209. log += (index === 0 ? "\n\tMeshes:" : "");
  70210. log += "\n\t\t" + mesh.toString(fullDetails);
  70211. }
  70212. }
  70213. // Cameras
  70214. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  70215. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  70216. var parsedCamera = parsedData.cameras[index];
  70217. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  70218. container.cameras.push(camera);
  70219. log += (index === 0 ? "\n\tCameras:" : "");
  70220. log += "\n\t\t" + camera.toString(fullDetails);
  70221. }
  70222. }
  70223. // Browsing all the graph to connect the dots
  70224. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  70225. var camera = scene.cameras[index];
  70226. if (camera._waitingParentId) {
  70227. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  70228. camera._waitingParentId = null;
  70229. }
  70230. }
  70231. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70232. var light_1 = scene.lights[index];
  70233. if (light_1 && light_1._waitingParentId) {
  70234. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  70235. light_1._waitingParentId = null;
  70236. }
  70237. }
  70238. // Sounds
  70239. // TODO: add sound
  70240. var loadedSounds = [];
  70241. var loadedSound;
  70242. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70243. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70244. var parsedSound = parsedData.sounds[index];
  70245. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70246. if (!parsedSound.url)
  70247. parsedSound.url = parsedSound.name;
  70248. if (!loadedSounds[parsedSound.url]) {
  70249. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70250. loadedSounds[parsedSound.url] = loadedSound;
  70251. container.sounds.push(loadedSound);
  70252. }
  70253. else {
  70254. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70255. }
  70256. }
  70257. else {
  70258. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70259. }
  70260. }
  70261. }
  70262. loadedSounds = [];
  70263. // Connect parents & children and parse actions
  70264. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  70265. var transformNode = scene.transformNodes[index];
  70266. if (transformNode._waitingParentId) {
  70267. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  70268. transformNode._waitingParentId = null;
  70269. }
  70270. }
  70271. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70272. var mesh = scene.meshes[index];
  70273. if (mesh._waitingParentId) {
  70274. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  70275. mesh._waitingParentId = null;
  70276. }
  70277. if (mesh._waitingActions) {
  70278. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  70279. mesh._waitingActions = null;
  70280. }
  70281. }
  70282. // freeze world matrix application
  70283. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70284. var currentMesh = scene.meshes[index];
  70285. if (currentMesh._waitingFreezeWorldMatrix) {
  70286. currentMesh.freezeWorldMatrix();
  70287. currentMesh._waitingFreezeWorldMatrix = null;
  70288. }
  70289. else {
  70290. currentMesh.computeWorldMatrix(true);
  70291. }
  70292. }
  70293. // Shadows
  70294. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  70295. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  70296. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  70297. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  70298. // SG would be available on their associated lights
  70299. }
  70300. }
  70301. // Lights exclusions / inclusions
  70302. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70303. var light_2 = scene.lights[index];
  70304. // Excluded check
  70305. if (light_2._excludedMeshesIds.length > 0) {
  70306. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  70307. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  70308. if (excludedMesh) {
  70309. light_2.excludedMeshes.push(excludedMesh);
  70310. }
  70311. }
  70312. light_2._excludedMeshesIds = [];
  70313. }
  70314. // Included check
  70315. if (light_2._includedOnlyMeshesIds.length > 0) {
  70316. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  70317. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  70318. if (includedOnlyMesh) {
  70319. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  70320. }
  70321. }
  70322. light_2._includedOnlyMeshesIds = [];
  70323. }
  70324. }
  70325. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  70326. // Actions (scene)
  70327. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  70328. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  70329. }
  70330. if (!addToScene) {
  70331. container.removeAllFromScene();
  70332. }
  70333. }
  70334. catch (err) {
  70335. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  70336. if (onError) {
  70337. onError(msg, err);
  70338. }
  70339. else {
  70340. BABYLON.Tools.Log(msg);
  70341. throw err;
  70342. }
  70343. }
  70344. finally {
  70345. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70346. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70347. }
  70348. }
  70349. return container;
  70350. };
  70351. BABYLON.SceneLoader.RegisterPlugin({
  70352. name: "babylon.js",
  70353. extensions: ".babylon",
  70354. canDirectLoad: function (data) {
  70355. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  70356. return true;
  70357. }
  70358. return false;
  70359. },
  70360. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  70361. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70362. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70363. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70364. // and avoid problems with multiple concurrent .babylon loads.
  70365. var log = "importMesh has failed JSON parse";
  70366. try {
  70367. var parsedData = JSON.parse(data);
  70368. log = "";
  70369. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70370. if (!meshesNames) {
  70371. meshesNames = null;
  70372. }
  70373. else if (!Array.isArray(meshesNames)) {
  70374. meshesNames = [meshesNames];
  70375. }
  70376. var hierarchyIds = new Array();
  70377. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70378. var loadedSkeletonsIds = [];
  70379. var loadedMaterialsIds = [];
  70380. var index;
  70381. var cache;
  70382. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70383. var parsedMesh = parsedData.meshes[index];
  70384. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  70385. if (meshesNames !== null) {
  70386. // Remove found mesh name from list.
  70387. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  70388. }
  70389. //Geometry?
  70390. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  70391. //does the file contain geometries?
  70392. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  70393. //find the correct geometry and add it to the scene
  70394. var found = false;
  70395. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  70396. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  70397. return;
  70398. }
  70399. else {
  70400. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  70401. if (parsedGeometryData.id === parsedMesh.geometryId) {
  70402. switch (geometryType) {
  70403. case "boxes":
  70404. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  70405. break;
  70406. case "spheres":
  70407. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  70408. break;
  70409. case "cylinders":
  70410. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  70411. break;
  70412. case "toruses":
  70413. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  70414. break;
  70415. case "grounds":
  70416. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  70417. break;
  70418. case "planes":
  70419. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  70420. break;
  70421. case "torusKnots":
  70422. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  70423. break;
  70424. case "vertexData":
  70425. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  70426. break;
  70427. }
  70428. found = true;
  70429. }
  70430. });
  70431. }
  70432. });
  70433. if (found === false) {
  70434. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  70435. }
  70436. }
  70437. }
  70438. // Material ?
  70439. if (parsedMesh.materialId) {
  70440. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  70441. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70442. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  70443. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  70444. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  70445. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  70446. var subMatId = parsedMultiMaterial.materials[matIndex];
  70447. loadedMaterialsIds.push(subMatId);
  70448. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  70449. if (mat) {
  70450. log += "\n\tMaterial " + mat.toString(fullDetails);
  70451. }
  70452. }
  70453. loadedMaterialsIds.push(parsedMultiMaterial.id);
  70454. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70455. if (mmat) {
  70456. materialFound = true;
  70457. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  70458. }
  70459. break;
  70460. }
  70461. }
  70462. }
  70463. if (materialFound === false) {
  70464. loadedMaterialsIds.push(parsedMesh.materialId);
  70465. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  70466. if (!mat) {
  70467. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  70468. }
  70469. else {
  70470. log += "\n\tMaterial " + mat.toString(fullDetails);
  70471. }
  70472. }
  70473. }
  70474. // Skeleton ?
  70475. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70476. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  70477. if (skeletonAlreadyLoaded === false) {
  70478. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  70479. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  70480. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  70481. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70482. skeletons.push(skeleton);
  70483. loadedSkeletonsIds.push(parsedSkeleton.id);
  70484. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  70485. }
  70486. }
  70487. }
  70488. }
  70489. // Morph targets ?
  70490. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70491. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70492. var managerData = _a[_i];
  70493. BABYLON.MorphTargetManager.Parse(managerData, scene);
  70494. }
  70495. }
  70496. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70497. meshes.push(mesh);
  70498. log += "\n\tMesh " + mesh.toString(fullDetails);
  70499. }
  70500. }
  70501. // Connecting parents
  70502. var currentMesh;
  70503. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70504. currentMesh = scene.meshes[index];
  70505. if (currentMesh._waitingParentId) {
  70506. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  70507. currentMesh._waitingParentId = null;
  70508. }
  70509. }
  70510. // freeze and compute world matrix application
  70511. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70512. currentMesh = scene.meshes[index];
  70513. if (currentMesh._waitingFreezeWorldMatrix) {
  70514. currentMesh.freezeWorldMatrix();
  70515. currentMesh._waitingFreezeWorldMatrix = null;
  70516. }
  70517. else {
  70518. currentMesh.computeWorldMatrix(true);
  70519. }
  70520. }
  70521. }
  70522. // Particles
  70523. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  70524. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  70525. if (parser) {
  70526. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  70527. var parsedParticleSystem = parsedData.particleSystems[index];
  70528. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  70529. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  70530. }
  70531. }
  70532. }
  70533. }
  70534. return true;
  70535. }
  70536. catch (err) {
  70537. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  70538. if (onError) {
  70539. onError(msg, err);
  70540. }
  70541. else {
  70542. BABYLON.Tools.Log(msg);
  70543. throw err;
  70544. }
  70545. }
  70546. finally {
  70547. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70548. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70549. }
  70550. }
  70551. return false;
  70552. },
  70553. load: function (scene, data, rootUrl, onError) {
  70554. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70555. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70556. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70557. // and avoid problems with multiple concurrent .babylon loads.
  70558. var log = "importScene has failed JSON parse";
  70559. try {
  70560. var parsedData = JSON.parse(data);
  70561. log = "";
  70562. // Scene
  70563. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  70564. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  70565. }
  70566. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  70567. scene.autoClear = parsedData.autoClear;
  70568. }
  70569. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  70570. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  70571. }
  70572. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  70573. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  70574. }
  70575. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  70576. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  70577. }
  70578. // Fog
  70579. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  70580. scene.fogMode = parsedData.fogMode;
  70581. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  70582. scene.fogStart = parsedData.fogStart;
  70583. scene.fogEnd = parsedData.fogEnd;
  70584. scene.fogDensity = parsedData.fogDensity;
  70585. log += "\tFog mode for scene: ";
  70586. switch (scene.fogMode) {
  70587. // getters not compiling, so using hardcoded
  70588. case 1:
  70589. log += "exp\n";
  70590. break;
  70591. case 2:
  70592. log += "exp2\n";
  70593. break;
  70594. case 3:
  70595. log += "linear\n";
  70596. break;
  70597. }
  70598. }
  70599. //Physics
  70600. if (parsedData.physicsEnabled) {
  70601. var physicsPlugin;
  70602. if (parsedData.physicsEngine === "cannon") {
  70603. physicsPlugin = new BABYLON.CannonJSPlugin();
  70604. }
  70605. else if (parsedData.physicsEngine === "oimo") {
  70606. physicsPlugin = new BABYLON.OimoJSPlugin();
  70607. }
  70608. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  70609. //else - default engine, which is currently oimo
  70610. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  70611. scene.enablePhysics(physicsGravity, physicsPlugin);
  70612. }
  70613. // Metadata
  70614. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70615. scene.metadata = parsedData.metadata;
  70616. }
  70617. //collisions, if defined. otherwise, default is true
  70618. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70619. scene.collisionsEnabled = parsedData.collisionsEnabled;
  70620. }
  70621. scene.workerCollisions = !!parsedData.workerCollisions;
  70622. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  70623. if (!container) {
  70624. return false;
  70625. }
  70626. if (parsedData.autoAnimate) {
  70627. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  70628. }
  70629. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  70630. scene.setActiveCameraByID(parsedData.activeCameraID);
  70631. }
  70632. // Environment texture
  70633. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  70634. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  70635. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  70636. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  70637. if (parsedData.environmentTextureRotationY) {
  70638. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  70639. }
  70640. scene.environmentTexture = hdrTexture;
  70641. }
  70642. else {
  70643. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  70644. if (parsedData.environmentTextureRotationY) {
  70645. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  70646. }
  70647. scene.environmentTexture = cubeTexture;
  70648. }
  70649. if (parsedData.createDefaultSkybox === true) {
  70650. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  70651. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  70652. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  70653. }
  70654. }
  70655. // Finish
  70656. return true;
  70657. }
  70658. catch (err) {
  70659. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  70660. if (onError) {
  70661. onError(msg, err);
  70662. }
  70663. else {
  70664. BABYLON.Tools.Log(msg);
  70665. throw err;
  70666. }
  70667. }
  70668. finally {
  70669. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70670. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70671. }
  70672. }
  70673. return false;
  70674. },
  70675. loadAssetContainer: function (scene, data, rootUrl, onError) {
  70676. var container = loadAssetContainer(scene, data, rootUrl, onError);
  70677. return container;
  70678. }
  70679. });
  70680. })(BABYLON || (BABYLON = {}));
  70681. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  70682. var BABYLON;
  70683. (function (BABYLON) {
  70684. var FilesInput = /** @class */ (function () {
  70685. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  70686. this.onProcessFileCallback = function () { return true; };
  70687. this._engine = engine;
  70688. this._currentScene = scene;
  70689. this._sceneLoadedCallback = sceneLoadedCallback;
  70690. this._progressCallback = progressCallback;
  70691. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  70692. this._textureLoadingCallback = textureLoadingCallback;
  70693. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  70694. this._onReloadCallback = onReloadCallback;
  70695. this._errorCallback = errorCallback;
  70696. }
  70697. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  70698. var _this = this;
  70699. if (elementToMonitor) {
  70700. this._elementToMonitor = elementToMonitor;
  70701. this._dragEnterHandler = function (e) { _this.drag(e); };
  70702. this._dragOverHandler = function (e) { _this.drag(e); };
  70703. this._dropHandler = function (e) { _this.drop(e); };
  70704. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70705. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  70706. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  70707. }
  70708. };
  70709. FilesInput.prototype.dispose = function () {
  70710. if (!this._elementToMonitor) {
  70711. return;
  70712. }
  70713. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  70714. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  70715. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  70716. };
  70717. FilesInput.prototype.renderFunction = function () {
  70718. if (this._additionalRenderLoopLogicCallback) {
  70719. this._additionalRenderLoopLogicCallback();
  70720. }
  70721. if (this._currentScene) {
  70722. if (this._textureLoadingCallback) {
  70723. var remaining = this._currentScene.getWaitingItemsCount();
  70724. if (remaining > 0) {
  70725. this._textureLoadingCallback(remaining);
  70726. }
  70727. }
  70728. this._currentScene.render();
  70729. }
  70730. };
  70731. FilesInput.prototype.drag = function (e) {
  70732. e.stopPropagation();
  70733. e.preventDefault();
  70734. };
  70735. FilesInput.prototype.drop = function (eventDrop) {
  70736. eventDrop.stopPropagation();
  70737. eventDrop.preventDefault();
  70738. this.loadFiles(eventDrop);
  70739. };
  70740. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  70741. var _this = this;
  70742. var reader = folder.createReader();
  70743. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  70744. reader.readEntries(function (entries) {
  70745. remaining.count += entries.length;
  70746. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  70747. var entry = entries_1[_i];
  70748. if (entry.isFile) {
  70749. entry.file(function (file) {
  70750. file.correctName = relativePath + file.name;
  70751. files.push(file);
  70752. if (--remaining.count === 0) {
  70753. callback();
  70754. }
  70755. });
  70756. }
  70757. else if (entry.isDirectory) {
  70758. _this._traverseFolder(entry, files, remaining, callback);
  70759. }
  70760. }
  70761. if (--remaining.count) {
  70762. callback();
  70763. }
  70764. });
  70765. };
  70766. FilesInput.prototype._processFiles = function (files) {
  70767. for (var i = 0; i < files.length; i++) {
  70768. var name = files[i].correctName.toLowerCase();
  70769. var extension = name.split('.').pop();
  70770. if (!this.onProcessFileCallback(files[i], name, extension)) {
  70771. continue;
  70772. }
  70773. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  70774. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  70775. this._sceneFileToLoad = files[i];
  70776. }
  70777. else {
  70778. FilesInput.FilesToLoad[name] = files[i];
  70779. }
  70780. }
  70781. };
  70782. FilesInput.prototype.loadFiles = function (event) {
  70783. var _this = this;
  70784. if (this._startingProcessingFilesCallback)
  70785. this._startingProcessingFilesCallback();
  70786. // Handling data transfer via drag'n'drop
  70787. if (event && event.dataTransfer && event.dataTransfer.files) {
  70788. this._filesToLoad = event.dataTransfer.files;
  70789. }
  70790. // Handling files from input files
  70791. if (event && event.target && event.target.files) {
  70792. this._filesToLoad = event.target.files;
  70793. }
  70794. if (this._filesToLoad && this._filesToLoad.length > 0) {
  70795. var files_1 = new Array();
  70796. var folders = [];
  70797. var items = event.dataTransfer ? event.dataTransfer.items : null;
  70798. for (var i = 0; i < this._filesToLoad.length; i++) {
  70799. var fileToLoad = this._filesToLoad[i];
  70800. var name_1 = fileToLoad.name.toLowerCase();
  70801. var entry = void 0;
  70802. fileToLoad.correctName = name_1;
  70803. if (items) {
  70804. var item = items[i];
  70805. if (item.getAsEntry) {
  70806. entry = item.getAsEntry();
  70807. }
  70808. else if (item.webkitGetAsEntry) {
  70809. entry = item.webkitGetAsEntry();
  70810. }
  70811. }
  70812. if (!entry) {
  70813. files_1.push(fileToLoad);
  70814. }
  70815. else {
  70816. if (entry.isDirectory) {
  70817. folders.push(entry);
  70818. }
  70819. else {
  70820. files_1.push(fileToLoad);
  70821. }
  70822. }
  70823. }
  70824. if (folders.length === 0) {
  70825. this._processFiles(files_1);
  70826. this._processReload();
  70827. }
  70828. else {
  70829. var remaining = { count: folders.length };
  70830. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  70831. var folder = folders_1[_i];
  70832. this._traverseFolder(folder, files_1, remaining, function () {
  70833. _this._processFiles(files_1);
  70834. if (remaining.count === 0) {
  70835. _this._processReload();
  70836. }
  70837. });
  70838. }
  70839. }
  70840. }
  70841. };
  70842. FilesInput.prototype._processReload = function () {
  70843. if (this._onReloadCallback) {
  70844. this._onReloadCallback(this._sceneFileToLoad);
  70845. }
  70846. else {
  70847. this.reload();
  70848. }
  70849. };
  70850. FilesInput.prototype.reload = function () {
  70851. var _this = this;
  70852. // If a scene file has been provided
  70853. if (this._sceneFileToLoad) {
  70854. if (this._currentScene) {
  70855. if (BABYLON.Tools.errorsCount > 0) {
  70856. BABYLON.Tools.ClearLogCache();
  70857. }
  70858. this._engine.stopRenderLoop();
  70859. }
  70860. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  70861. if (_this._progressCallback) {
  70862. _this._progressCallback(progress);
  70863. }
  70864. }).then(function (scene) {
  70865. if (_this._currentScene) {
  70866. _this._currentScene.dispose();
  70867. }
  70868. _this._currentScene = scene;
  70869. if (_this._sceneLoadedCallback) {
  70870. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  70871. }
  70872. // Wait for textures and shaders to be ready
  70873. _this._currentScene.executeWhenReady(function () {
  70874. _this._engine.runRenderLoop(function () {
  70875. _this.renderFunction();
  70876. });
  70877. });
  70878. }).catch(function (error) {
  70879. if (_this._errorCallback) {
  70880. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  70881. }
  70882. });
  70883. }
  70884. else {
  70885. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  70886. }
  70887. };
  70888. FilesInput.FilesToLoad = {};
  70889. return FilesInput;
  70890. }());
  70891. BABYLON.FilesInput = FilesInput;
  70892. })(BABYLON || (BABYLON = {}));
  70893. //# sourceMappingURL=babylon.filesInput.js.map
  70894. var BABYLON;
  70895. (function (BABYLON) {
  70896. var Tags = /** @class */ (function () {
  70897. function Tags() {
  70898. }
  70899. Tags.EnableFor = function (obj) {
  70900. obj._tags = obj._tags || {};
  70901. obj.hasTags = function () {
  70902. return Tags.HasTags(obj);
  70903. };
  70904. obj.addTags = function (tagsString) {
  70905. return Tags.AddTagsTo(obj, tagsString);
  70906. };
  70907. obj.removeTags = function (tagsString) {
  70908. return Tags.RemoveTagsFrom(obj, tagsString);
  70909. };
  70910. obj.matchesTagsQuery = function (tagsQuery) {
  70911. return Tags.MatchesQuery(obj, tagsQuery);
  70912. };
  70913. };
  70914. Tags.DisableFor = function (obj) {
  70915. delete obj._tags;
  70916. delete obj.hasTags;
  70917. delete obj.addTags;
  70918. delete obj.removeTags;
  70919. delete obj.matchesTagsQuery;
  70920. };
  70921. Tags.HasTags = function (obj) {
  70922. if (!obj._tags) {
  70923. return false;
  70924. }
  70925. return !BABYLON.Tools.IsEmpty(obj._tags);
  70926. };
  70927. Tags.GetTags = function (obj, asString) {
  70928. if (asString === void 0) { asString = true; }
  70929. if (!obj._tags) {
  70930. return null;
  70931. }
  70932. if (asString) {
  70933. var tagsArray = [];
  70934. for (var tag in obj._tags) {
  70935. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  70936. tagsArray.push(tag);
  70937. }
  70938. }
  70939. return tagsArray.join(" ");
  70940. }
  70941. else {
  70942. return obj._tags;
  70943. }
  70944. };
  70945. // the tags 'true' and 'false' are reserved and cannot be used as tags
  70946. // a tag cannot start with '||', '&&', and '!'
  70947. // it cannot contain whitespaces
  70948. Tags.AddTagsTo = function (obj, tagsString) {
  70949. if (!tagsString) {
  70950. return;
  70951. }
  70952. if (typeof tagsString !== "string") {
  70953. return;
  70954. }
  70955. var tags = tagsString.split(" ");
  70956. tags.forEach(function (tag, index, array) {
  70957. Tags._AddTagTo(obj, tag);
  70958. });
  70959. };
  70960. Tags._AddTagTo = function (obj, tag) {
  70961. tag = tag.trim();
  70962. if (tag === "" || tag === "true" || tag === "false") {
  70963. return;
  70964. }
  70965. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  70966. return;
  70967. }
  70968. Tags.EnableFor(obj);
  70969. obj._tags[tag] = true;
  70970. };
  70971. Tags.RemoveTagsFrom = function (obj, tagsString) {
  70972. if (!Tags.HasTags(obj)) {
  70973. return;
  70974. }
  70975. var tags = tagsString.split(" ");
  70976. for (var t in tags) {
  70977. Tags._RemoveTagFrom(obj, tags[t]);
  70978. }
  70979. };
  70980. Tags._RemoveTagFrom = function (obj, tag) {
  70981. delete obj._tags[tag];
  70982. };
  70983. Tags.MatchesQuery = function (obj, tagsQuery) {
  70984. if (tagsQuery === undefined) {
  70985. return true;
  70986. }
  70987. if (tagsQuery === "") {
  70988. return Tags.HasTags(obj);
  70989. }
  70990. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  70991. };
  70992. return Tags;
  70993. }());
  70994. BABYLON.Tags = Tags;
  70995. })(BABYLON || (BABYLON = {}));
  70996. //# sourceMappingURL=babylon.tags.js.map
  70997. var BABYLON;
  70998. (function (BABYLON) {
  70999. /**
  71000. * Class used to evalaute queries containing `and` and `or` operators
  71001. */
  71002. var AndOrNotEvaluator = /** @class */ (function () {
  71003. function AndOrNotEvaluator() {
  71004. }
  71005. /**
  71006. * Evaluate a query
  71007. * @param query defines the query to evaluate
  71008. * @param evaluateCallback defines the callback used to filter result
  71009. * @returns true if the query matches
  71010. */
  71011. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  71012. if (!query.match(/\([^\(\)]*\)/g)) {
  71013. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  71014. }
  71015. else {
  71016. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  71017. // remove parenthesis
  71018. r = r.slice(1, r.length - 1);
  71019. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  71020. });
  71021. }
  71022. if (query === "true") {
  71023. return true;
  71024. }
  71025. if (query === "false") {
  71026. return false;
  71027. }
  71028. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  71029. };
  71030. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  71031. evaluateCallback = evaluateCallback || (function (r) {
  71032. return r === "true" ? true : false;
  71033. });
  71034. var result;
  71035. var or = parenthesisContent.split("||");
  71036. for (var i in or) {
  71037. if (or.hasOwnProperty(i)) {
  71038. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  71039. var and = ori.split("&&");
  71040. if (and.length > 1) {
  71041. for (var j = 0; j < and.length; ++j) {
  71042. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  71043. if (andj !== "true" && andj !== "false") {
  71044. if (andj[0] === "!") {
  71045. result = !evaluateCallback(andj.substring(1));
  71046. }
  71047. else {
  71048. result = evaluateCallback(andj);
  71049. }
  71050. }
  71051. else {
  71052. result = andj === "true" ? true : false;
  71053. }
  71054. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  71055. ori = "false";
  71056. break;
  71057. }
  71058. }
  71059. }
  71060. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  71061. result = true;
  71062. break;
  71063. }
  71064. // result equals false (or undefined)
  71065. if (ori !== "true" && ori !== "false") {
  71066. if (ori[0] === "!") {
  71067. result = !evaluateCallback(ori.substring(1));
  71068. }
  71069. else {
  71070. result = evaluateCallback(ori);
  71071. }
  71072. }
  71073. else {
  71074. result = ori === "true" ? true : false;
  71075. }
  71076. }
  71077. }
  71078. // the whole parenthesis scope is replaced by 'true' or 'false'
  71079. return result ? "true" : "false";
  71080. };
  71081. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  71082. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  71083. // remove whitespaces
  71084. r = r.replace(/[\s]/g, function () { return ""; });
  71085. return r.length % 2 ? "!" : "";
  71086. });
  71087. booleanString = booleanString.trim();
  71088. if (booleanString === "!true") {
  71089. booleanString = "false";
  71090. }
  71091. else if (booleanString === "!false") {
  71092. booleanString = "true";
  71093. }
  71094. return booleanString;
  71095. };
  71096. return AndOrNotEvaluator;
  71097. }());
  71098. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  71099. })(BABYLON || (BABYLON = {}));
  71100. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  71101. var BABYLON;
  71102. (function (BABYLON) {
  71103. /**
  71104. * Class used to enable access to IndexedDB
  71105. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  71106. */
  71107. var Database = /** @class */ (function () {
  71108. /**
  71109. * Creates a new Database
  71110. * @param urlToScene defines the url to load the scene
  71111. * @param callbackManifestChecked defines the callback to use when manifest is checked
  71112. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  71113. */
  71114. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  71115. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  71116. var _this = this;
  71117. // Handling various flavors of prefixed version of IndexedDB
  71118. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  71119. this.callbackManifestChecked = callbackManifestChecked;
  71120. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  71121. this.db = null;
  71122. this._enableSceneOffline = false;
  71123. this._enableTexturesOffline = false;
  71124. this.manifestVersionFound = 0;
  71125. this.mustUpdateRessources = false;
  71126. this.hasReachedQuota = false;
  71127. if (!Database.IDBStorageEnabled) {
  71128. this.callbackManifestChecked(true);
  71129. }
  71130. else {
  71131. if (disableManifestCheck) {
  71132. this._enableSceneOffline = true;
  71133. this._enableTexturesOffline = true;
  71134. this.manifestVersionFound = 1;
  71135. BABYLON.Tools.SetImmediate(function () {
  71136. _this.callbackManifestChecked(true);
  71137. });
  71138. }
  71139. else {
  71140. this._checkManifestFile();
  71141. }
  71142. }
  71143. }
  71144. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  71145. /**
  71146. * Gets a boolean indicating if scene must be saved in the database
  71147. */
  71148. get: function () {
  71149. return this._enableSceneOffline;
  71150. },
  71151. enumerable: true,
  71152. configurable: true
  71153. });
  71154. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  71155. /**
  71156. * Gets a boolean indicating if textures must be saved in the database
  71157. */
  71158. get: function () {
  71159. return this._enableTexturesOffline;
  71160. },
  71161. enumerable: true,
  71162. configurable: true
  71163. });
  71164. Database.prototype._checkManifestFile = function () {
  71165. var _this = this;
  71166. var noManifestFile = function () {
  71167. _this._enableSceneOffline = false;
  71168. _this._enableTexturesOffline = false;
  71169. _this.callbackManifestChecked(false);
  71170. };
  71171. var timeStampUsed = false;
  71172. var manifestURL = this.currentSceneUrl + ".manifest";
  71173. var xhr = new XMLHttpRequest();
  71174. if (navigator.onLine) {
  71175. // Adding a timestamp to by-pass browsers' cache
  71176. timeStampUsed = true;
  71177. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  71178. }
  71179. xhr.open("GET", manifestURL, true);
  71180. xhr.addEventListener("load", function () {
  71181. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71182. try {
  71183. var manifestFile = JSON.parse(xhr.response);
  71184. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  71185. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  71186. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  71187. _this.manifestVersionFound = manifestFile.version;
  71188. }
  71189. if (_this.callbackManifestChecked) {
  71190. _this.callbackManifestChecked(true);
  71191. }
  71192. }
  71193. catch (ex) {
  71194. noManifestFile();
  71195. }
  71196. }
  71197. else {
  71198. noManifestFile();
  71199. }
  71200. }, false);
  71201. xhr.addEventListener("error", function (event) {
  71202. if (timeStampUsed) {
  71203. timeStampUsed = false;
  71204. // Let's retry without the timeStamp
  71205. // It could fail when coupled with HTML5 Offline API
  71206. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  71207. xhr.open("GET", retryManifestURL, true);
  71208. xhr.send();
  71209. }
  71210. else {
  71211. noManifestFile();
  71212. }
  71213. }, false);
  71214. try {
  71215. xhr.send();
  71216. }
  71217. catch (ex) {
  71218. BABYLON.Tools.Error("Error on XHR send request.");
  71219. this.callbackManifestChecked(false);
  71220. }
  71221. };
  71222. /**
  71223. * Open the database and make it available
  71224. * @param successCallback defines the callback to call on success
  71225. * @param errorCallback defines the callback to call on error
  71226. */
  71227. Database.prototype.openAsync = function (successCallback, errorCallback) {
  71228. var _this = this;
  71229. var handleError = function () {
  71230. _this.isSupported = false;
  71231. if (errorCallback)
  71232. errorCallback();
  71233. };
  71234. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  71235. // Your browser doesn't support IndexedDB
  71236. this.isSupported = false;
  71237. if (errorCallback)
  71238. errorCallback();
  71239. }
  71240. else {
  71241. // If the DB hasn't been opened or created yet
  71242. if (!this.db) {
  71243. this.hasReachedQuota = false;
  71244. this.isSupported = true;
  71245. var request = this.idbFactory.open("babylonjs", 1);
  71246. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  71247. request.onerror = function (event) {
  71248. handleError();
  71249. };
  71250. // executes when a version change transaction cannot complete due to other active transactions
  71251. request.onblocked = function (event) {
  71252. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  71253. handleError();
  71254. };
  71255. // DB has been opened successfully
  71256. request.onsuccess = function (event) {
  71257. _this.db = request.result;
  71258. successCallback();
  71259. };
  71260. // Initialization of the DB. Creating Scenes & Textures stores
  71261. request.onupgradeneeded = function (event) {
  71262. _this.db = (event.target).result;
  71263. if (_this.db) {
  71264. try {
  71265. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  71266. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  71267. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  71268. }
  71269. catch (ex) {
  71270. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  71271. handleError();
  71272. }
  71273. }
  71274. };
  71275. }
  71276. // DB has already been created and opened
  71277. else {
  71278. if (successCallback)
  71279. successCallback();
  71280. }
  71281. }
  71282. };
  71283. /**
  71284. * Loads an image from the database
  71285. * @param url defines the url to load from
  71286. * @param image defines the target DOM image
  71287. */
  71288. Database.prototype.loadImageFromDB = function (url, image) {
  71289. var _this = this;
  71290. var completeURL = Database._ReturnFullUrlLocation(url);
  71291. var saveAndLoadImage = function () {
  71292. if (!_this.hasReachedQuota && _this.db !== null) {
  71293. // the texture is not yet in the DB, let's try to save it
  71294. _this._saveImageIntoDBAsync(completeURL, image);
  71295. }
  71296. // If the texture is not in the DB and we've reached the DB quota limit
  71297. // let's load it directly from the web
  71298. else {
  71299. image.src = url;
  71300. }
  71301. };
  71302. if (!this.mustUpdateRessources) {
  71303. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  71304. }
  71305. // First time we're download the images or update requested in the manifest file by a version change
  71306. else {
  71307. saveAndLoadImage();
  71308. }
  71309. };
  71310. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  71311. if (this.isSupported && this.db !== null) {
  71312. var texture;
  71313. var transaction = this.db.transaction(["textures"]);
  71314. transaction.onabort = function (event) {
  71315. image.src = url;
  71316. };
  71317. transaction.oncomplete = function (event) {
  71318. var blobTextureURL;
  71319. if (texture) {
  71320. var URL = window.URL || window.webkitURL;
  71321. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  71322. image.onerror = function () {
  71323. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  71324. image.src = url;
  71325. };
  71326. image.src = blobTextureURL;
  71327. }
  71328. else {
  71329. notInDBCallback();
  71330. }
  71331. };
  71332. var getRequest = transaction.objectStore("textures").get(url);
  71333. getRequest.onsuccess = function (event) {
  71334. texture = (event.target).result;
  71335. };
  71336. getRequest.onerror = function (event) {
  71337. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  71338. image.src = url;
  71339. };
  71340. }
  71341. else {
  71342. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71343. image.src = url;
  71344. }
  71345. };
  71346. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  71347. var _this = this;
  71348. if (this.isSupported) {
  71349. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  71350. var generateBlobUrl = function () {
  71351. var blobTextureURL;
  71352. if (blob) {
  71353. var URL = window.URL || window.webkitURL;
  71354. try {
  71355. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  71356. }
  71357. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  71358. catch (ex) {
  71359. blobTextureURL = URL.createObjectURL(blob);
  71360. }
  71361. }
  71362. if (blobTextureURL) {
  71363. image.src = blobTextureURL;
  71364. }
  71365. };
  71366. if (Database.IsUASupportingBlobStorage) { // Create XHR
  71367. var xhr = new XMLHttpRequest(), blob;
  71368. xhr.open("GET", url, true);
  71369. xhr.responseType = "blob";
  71370. xhr.addEventListener("load", function () {
  71371. if (xhr.status === 200 && _this.db) {
  71372. // Blob as response (XHR2)
  71373. blob = xhr.response;
  71374. var transaction = _this.db.transaction(["textures"], "readwrite");
  71375. // the transaction could abort because of a QuotaExceededError error
  71376. transaction.onabort = function (event) {
  71377. try {
  71378. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71379. var srcElement = (event.srcElement || event.target);
  71380. var error = srcElement.error;
  71381. if (error && error.name === "QuotaExceededError") {
  71382. _this.hasReachedQuota = true;
  71383. }
  71384. }
  71385. catch (ex) { }
  71386. generateBlobUrl();
  71387. };
  71388. transaction.oncomplete = function (event) {
  71389. generateBlobUrl();
  71390. };
  71391. var newTexture = { textureUrl: url, data: blob };
  71392. try {
  71393. // Put the blob into the dabase
  71394. var addRequest = transaction.objectStore("textures").put(newTexture);
  71395. addRequest.onsuccess = function (event) {
  71396. };
  71397. addRequest.onerror = function (event) {
  71398. generateBlobUrl();
  71399. };
  71400. }
  71401. catch (ex) {
  71402. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  71403. if (ex.code === 25) {
  71404. Database.IsUASupportingBlobStorage = false;
  71405. }
  71406. image.src = url;
  71407. }
  71408. }
  71409. else {
  71410. image.src = url;
  71411. }
  71412. }, false);
  71413. xhr.addEventListener("error", function (event) {
  71414. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  71415. image.src = url;
  71416. }, false);
  71417. xhr.send();
  71418. }
  71419. else {
  71420. image.src = url;
  71421. }
  71422. }
  71423. else {
  71424. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71425. image.src = url;
  71426. }
  71427. };
  71428. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  71429. var _this = this;
  71430. var updateVersion = function () {
  71431. // the version is not yet in the DB or we need to update it
  71432. _this._saveVersionIntoDBAsync(url, versionLoaded);
  71433. };
  71434. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  71435. };
  71436. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  71437. var _this = this;
  71438. if (this.isSupported && this.db) {
  71439. var version;
  71440. try {
  71441. var transaction = this.db.transaction(["versions"]);
  71442. transaction.oncomplete = function (event) {
  71443. if (version) {
  71444. // If the version in the JSON file is different from the version in DB
  71445. if (_this.manifestVersionFound !== version.data) {
  71446. _this.mustUpdateRessources = true;
  71447. updateInDBCallback();
  71448. }
  71449. else {
  71450. callback(version.data);
  71451. }
  71452. }
  71453. // version was not found in DB
  71454. else {
  71455. _this.mustUpdateRessources = true;
  71456. updateInDBCallback();
  71457. }
  71458. };
  71459. transaction.onabort = function (event) {
  71460. callback(-1);
  71461. };
  71462. var getRequest = transaction.objectStore("versions").get(url);
  71463. getRequest.onsuccess = function (event) {
  71464. version = (event.target).result;
  71465. };
  71466. getRequest.onerror = function (event) {
  71467. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  71468. callback(-1);
  71469. };
  71470. }
  71471. catch (ex) {
  71472. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  71473. callback(-1);
  71474. }
  71475. }
  71476. else {
  71477. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71478. callback(-1);
  71479. }
  71480. };
  71481. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  71482. var _this = this;
  71483. if (this.isSupported && !this.hasReachedQuota && this.db) {
  71484. try {
  71485. // Open a transaction to the database
  71486. var transaction = this.db.transaction(["versions"], "readwrite");
  71487. // the transaction could abort because of a QuotaExceededError error
  71488. transaction.onabort = function (event) {
  71489. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71490. var error = event.srcElement['error'];
  71491. if (error && error.name === "QuotaExceededError") {
  71492. _this.hasReachedQuota = true;
  71493. }
  71494. }
  71495. catch (ex) { }
  71496. callback(-1);
  71497. };
  71498. transaction.oncomplete = function (event) {
  71499. callback(_this.manifestVersionFound);
  71500. };
  71501. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  71502. // Put the scene into the database
  71503. var addRequest = transaction.objectStore("versions").put(newVersion);
  71504. addRequest.onsuccess = function (event) {
  71505. };
  71506. addRequest.onerror = function (event) {
  71507. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  71508. };
  71509. }
  71510. catch (ex) {
  71511. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  71512. callback(-1);
  71513. }
  71514. }
  71515. else {
  71516. callback(-1);
  71517. }
  71518. };
  71519. /**
  71520. * Loads a file from database
  71521. * @param url defines the URL to load from
  71522. * @param sceneLoaded defines a callback to call on success
  71523. * @param progressCallBack defines a callback to call when progress changed
  71524. * @param errorCallback defines a callback to call on error
  71525. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  71526. */
  71527. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  71528. var _this = this;
  71529. var completeUrl = Database._ReturnFullUrlLocation(url);
  71530. var saveAndLoadFile = function () {
  71531. // the scene is not yet in the DB, let's try to save it
  71532. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71533. };
  71534. this._checkVersionFromDB(completeUrl, function (version) {
  71535. if (version !== -1) {
  71536. if (!_this.mustUpdateRessources) {
  71537. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  71538. }
  71539. else {
  71540. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71541. }
  71542. }
  71543. else {
  71544. if (errorCallback) {
  71545. errorCallback();
  71546. }
  71547. }
  71548. });
  71549. };
  71550. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  71551. if (this.isSupported && this.db) {
  71552. var targetStore;
  71553. if (url.indexOf(".babylon") !== -1) {
  71554. targetStore = "scenes";
  71555. }
  71556. else {
  71557. targetStore = "textures";
  71558. }
  71559. var file;
  71560. var transaction = this.db.transaction([targetStore]);
  71561. transaction.oncomplete = function (event) {
  71562. if (file) {
  71563. callback(file.data);
  71564. }
  71565. // file was not found in DB
  71566. else {
  71567. notInDBCallback();
  71568. }
  71569. };
  71570. transaction.onabort = function (event) {
  71571. notInDBCallback();
  71572. };
  71573. var getRequest = transaction.objectStore(targetStore).get(url);
  71574. getRequest.onsuccess = function (event) {
  71575. file = (event.target).result;
  71576. };
  71577. getRequest.onerror = function (event) {
  71578. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  71579. notInDBCallback();
  71580. };
  71581. }
  71582. else {
  71583. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71584. callback();
  71585. }
  71586. };
  71587. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  71588. var _this = this;
  71589. if (this.isSupported) {
  71590. var targetStore;
  71591. if (url.indexOf(".babylon") !== -1) {
  71592. targetStore = "scenes";
  71593. }
  71594. else {
  71595. targetStore = "textures";
  71596. }
  71597. // Create XHR
  71598. var xhr = new XMLHttpRequest();
  71599. var fileData;
  71600. xhr.open("GET", url + "?" + Date.now(), true);
  71601. if (useArrayBuffer) {
  71602. xhr.responseType = "arraybuffer";
  71603. }
  71604. if (progressCallback) {
  71605. xhr.onprogress = progressCallback;
  71606. }
  71607. xhr.addEventListener("load", function () {
  71608. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  71609. // Blob as response (XHR2)
  71610. //fileData = xhr.responseText;
  71611. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  71612. if (!_this.hasReachedQuota && _this.db) {
  71613. // Open a transaction to the database
  71614. var transaction = _this.db.transaction([targetStore], "readwrite");
  71615. // the transaction could abort because of a QuotaExceededError error
  71616. transaction.onabort = function (event) {
  71617. try {
  71618. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71619. var error = event.srcElement['error'];
  71620. if (error && error.name === "QuotaExceededError") {
  71621. _this.hasReachedQuota = true;
  71622. }
  71623. }
  71624. catch (ex) { }
  71625. callback(fileData);
  71626. };
  71627. transaction.oncomplete = function (event) {
  71628. callback(fileData);
  71629. };
  71630. var newFile;
  71631. if (targetStore === "scenes") {
  71632. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  71633. }
  71634. else {
  71635. newFile = { textureUrl: url, data: fileData };
  71636. }
  71637. try {
  71638. // Put the scene into the database
  71639. var addRequest = transaction.objectStore(targetStore).put(newFile);
  71640. addRequest.onsuccess = function (event) {
  71641. };
  71642. addRequest.onerror = function (event) {
  71643. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  71644. };
  71645. }
  71646. catch (ex) {
  71647. callback(fileData);
  71648. }
  71649. }
  71650. else {
  71651. callback(fileData);
  71652. }
  71653. }
  71654. else {
  71655. if (xhr.status >= 400 && errorCallback) {
  71656. errorCallback(xhr);
  71657. }
  71658. else {
  71659. callback();
  71660. }
  71661. }
  71662. }, false);
  71663. xhr.addEventListener("error", function (event) {
  71664. BABYLON.Tools.Error("error on XHR request.");
  71665. callback();
  71666. }, false);
  71667. xhr.send();
  71668. }
  71669. else {
  71670. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71671. callback();
  71672. }
  71673. };
  71674. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  71675. Database.IsUASupportingBlobStorage = true;
  71676. /** Gets a boolean indicating if Database storate is enabled */
  71677. Database.IDBStorageEnabled = true;
  71678. Database._ParseURL = function (url) {
  71679. var a = document.createElement('a');
  71680. a.href = url;
  71681. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  71682. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  71683. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  71684. return absLocation;
  71685. };
  71686. Database._ReturnFullUrlLocation = function (url) {
  71687. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  71688. return (Database._ParseURL(window.location.href) + url);
  71689. }
  71690. else {
  71691. return url;
  71692. }
  71693. };
  71694. return Database;
  71695. }());
  71696. BABYLON.Database = Database;
  71697. })(BABYLON || (BABYLON = {}));
  71698. //# sourceMappingURL=babylon.database.js.map
  71699. var BABYLON;
  71700. (function (BABYLON) {
  71701. var FresnelParameters = /** @class */ (function () {
  71702. function FresnelParameters() {
  71703. this._isEnabled = true;
  71704. this.leftColor = BABYLON.Color3.White();
  71705. this.rightColor = BABYLON.Color3.Black();
  71706. this.bias = 0;
  71707. this.power = 1;
  71708. }
  71709. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  71710. get: function () {
  71711. return this._isEnabled;
  71712. },
  71713. set: function (value) {
  71714. if (this._isEnabled === value) {
  71715. return;
  71716. }
  71717. this._isEnabled = value;
  71718. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  71719. },
  71720. enumerable: true,
  71721. configurable: true
  71722. });
  71723. FresnelParameters.prototype.clone = function () {
  71724. var newFresnelParameters = new FresnelParameters();
  71725. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  71726. return newFresnelParameters;
  71727. };
  71728. FresnelParameters.prototype.serialize = function () {
  71729. var serializationObject = {};
  71730. serializationObject.isEnabled = this.isEnabled;
  71731. serializationObject.leftColor = this.leftColor.asArray();
  71732. serializationObject.rightColor = this.rightColor.asArray();
  71733. serializationObject.bias = this.bias;
  71734. serializationObject.power = this.power;
  71735. return serializationObject;
  71736. };
  71737. FresnelParameters.Parse = function (parsedFresnelParameters) {
  71738. var fresnelParameters = new FresnelParameters();
  71739. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  71740. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  71741. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  71742. fresnelParameters.bias = parsedFresnelParameters.bias;
  71743. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  71744. return fresnelParameters;
  71745. };
  71746. return FresnelParameters;
  71747. }());
  71748. BABYLON.FresnelParameters = FresnelParameters;
  71749. })(BABYLON || (BABYLON = {}));
  71750. //# sourceMappingURL=babylon.fresnelParameters.js.map
  71751. var BABYLON;
  71752. (function (BABYLON) {
  71753. var MultiMaterial = /** @class */ (function (_super) {
  71754. __extends(MultiMaterial, _super);
  71755. function MultiMaterial(name, scene) {
  71756. var _this = _super.call(this, name, scene, true) || this;
  71757. scene.multiMaterials.push(_this);
  71758. _this.subMaterials = new Array();
  71759. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  71760. return _this;
  71761. }
  71762. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  71763. get: function () {
  71764. return this._subMaterials;
  71765. },
  71766. set: function (value) {
  71767. this._subMaterials = value;
  71768. this._hookArray(value);
  71769. },
  71770. enumerable: true,
  71771. configurable: true
  71772. });
  71773. MultiMaterial.prototype._hookArray = function (array) {
  71774. var _this = this;
  71775. var oldPush = array.push;
  71776. array.push = function () {
  71777. var items = [];
  71778. for (var _i = 0; _i < arguments.length; _i++) {
  71779. items[_i] = arguments[_i];
  71780. }
  71781. var result = oldPush.apply(array, items);
  71782. _this._markAllSubMeshesAsTexturesDirty();
  71783. return result;
  71784. };
  71785. var oldSplice = array.splice;
  71786. array.splice = function (index, deleteCount) {
  71787. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71788. _this._markAllSubMeshesAsTexturesDirty();
  71789. return deleted;
  71790. };
  71791. };
  71792. // Properties
  71793. MultiMaterial.prototype.getSubMaterial = function (index) {
  71794. if (index < 0 || index >= this.subMaterials.length) {
  71795. return this.getScene().defaultMaterial;
  71796. }
  71797. return this.subMaterials[index];
  71798. };
  71799. MultiMaterial.prototype.getActiveTextures = function () {
  71800. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  71801. if (subMaterial) {
  71802. return subMaterial.getActiveTextures();
  71803. }
  71804. else {
  71805. return [];
  71806. }
  71807. }));
  71808. var _a;
  71809. };
  71810. // Methods
  71811. MultiMaterial.prototype.getClassName = function () {
  71812. return "MultiMaterial";
  71813. };
  71814. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71815. for (var index = 0; index < this.subMaterials.length; index++) {
  71816. var subMaterial = this.subMaterials[index];
  71817. if (subMaterial) {
  71818. if (subMaterial.storeEffectOnSubMeshes) {
  71819. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  71820. return false;
  71821. }
  71822. continue;
  71823. }
  71824. if (!subMaterial.isReady(mesh)) {
  71825. return false;
  71826. }
  71827. }
  71828. }
  71829. return true;
  71830. };
  71831. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  71832. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  71833. for (var index = 0; index < this.subMaterials.length; index++) {
  71834. var subMaterial = null;
  71835. var current = this.subMaterials[index];
  71836. if (cloneChildren && current) {
  71837. subMaterial = current.clone(name + "-" + current.name);
  71838. }
  71839. else {
  71840. subMaterial = this.subMaterials[index];
  71841. }
  71842. newMultiMaterial.subMaterials.push(subMaterial);
  71843. }
  71844. return newMultiMaterial;
  71845. };
  71846. MultiMaterial.prototype.serialize = function () {
  71847. var serializationObject = {};
  71848. serializationObject.name = this.name;
  71849. serializationObject.id = this.id;
  71850. if (BABYLON.Tags) {
  71851. serializationObject.tags = BABYLON.Tags.GetTags(this);
  71852. }
  71853. serializationObject.materials = [];
  71854. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  71855. var subMat = this.subMaterials[matIndex];
  71856. if (subMat) {
  71857. serializationObject.materials.push(subMat.id);
  71858. }
  71859. else {
  71860. serializationObject.materials.push(null);
  71861. }
  71862. }
  71863. return serializationObject;
  71864. };
  71865. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  71866. var scene = this.getScene();
  71867. if (!scene) {
  71868. return;
  71869. }
  71870. var index = scene.multiMaterials.indexOf(this);
  71871. if (index >= 0) {
  71872. scene.multiMaterials.splice(index, 1);
  71873. }
  71874. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  71875. };
  71876. return MultiMaterial;
  71877. }(BABYLON.Material));
  71878. BABYLON.MultiMaterial = MultiMaterial;
  71879. })(BABYLON || (BABYLON = {}));
  71880. //# sourceMappingURL=babylon.multiMaterial.js.map
  71881. var BABYLON;
  71882. (function (BABYLON) {
  71883. var FreeCameraTouchInput = /** @class */ (function () {
  71884. function FreeCameraTouchInput() {
  71885. this._offsetX = null;
  71886. this._offsetY = null;
  71887. this._pointerPressed = new Array();
  71888. this.touchAngularSensibility = 200000.0;
  71889. this.touchMoveSensibility = 250.0;
  71890. }
  71891. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  71892. var _this = this;
  71893. var previousPosition = null;
  71894. if (this._pointerInput === undefined) {
  71895. this._onLostFocus = function (evt) {
  71896. _this._offsetX = null;
  71897. _this._offsetY = null;
  71898. };
  71899. this._pointerInput = function (p, s) {
  71900. var evt = p.event;
  71901. if (evt.pointerType === "mouse") {
  71902. return;
  71903. }
  71904. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71905. if (!noPreventDefault) {
  71906. evt.preventDefault();
  71907. }
  71908. _this._pointerPressed.push(evt.pointerId);
  71909. if (_this._pointerPressed.length !== 1) {
  71910. return;
  71911. }
  71912. previousPosition = {
  71913. x: evt.clientX,
  71914. y: evt.clientY
  71915. };
  71916. }
  71917. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  71918. if (!noPreventDefault) {
  71919. evt.preventDefault();
  71920. }
  71921. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71922. if (index === -1) {
  71923. return;
  71924. }
  71925. _this._pointerPressed.splice(index, 1);
  71926. if (index != 0) {
  71927. return;
  71928. }
  71929. previousPosition = null;
  71930. _this._offsetX = null;
  71931. _this._offsetY = null;
  71932. }
  71933. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  71934. if (!noPreventDefault) {
  71935. evt.preventDefault();
  71936. }
  71937. if (!previousPosition) {
  71938. return;
  71939. }
  71940. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71941. if (index != 0) {
  71942. return;
  71943. }
  71944. _this._offsetX = evt.clientX - previousPosition.x;
  71945. _this._offsetY = -(evt.clientY - previousPosition.y);
  71946. }
  71947. };
  71948. }
  71949. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  71950. if (this._onLostFocus) {
  71951. element.addEventListener("blur", this._onLostFocus);
  71952. }
  71953. };
  71954. FreeCameraTouchInput.prototype.detachControl = function (element) {
  71955. if (this._pointerInput && element) {
  71956. if (this._observer) {
  71957. this.camera.getScene().onPointerObservable.remove(this._observer);
  71958. this._observer = null;
  71959. }
  71960. if (this._onLostFocus) {
  71961. element.removeEventListener("blur", this._onLostFocus);
  71962. this._onLostFocus = null;
  71963. }
  71964. this._pointerPressed = [];
  71965. this._offsetX = null;
  71966. this._offsetY = null;
  71967. }
  71968. };
  71969. FreeCameraTouchInput.prototype.checkInputs = function () {
  71970. if (this._offsetX && this._offsetY) {
  71971. var camera = this.camera;
  71972. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  71973. if (this._pointerPressed.length > 1) {
  71974. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  71975. }
  71976. else {
  71977. var speed = camera._computeLocalCameraSpeed();
  71978. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  71979. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  71980. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  71981. }
  71982. }
  71983. };
  71984. FreeCameraTouchInput.prototype.getClassName = function () {
  71985. return "FreeCameraTouchInput";
  71986. };
  71987. FreeCameraTouchInput.prototype.getSimpleName = function () {
  71988. return "touch";
  71989. };
  71990. __decorate([
  71991. BABYLON.serialize()
  71992. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  71993. __decorate([
  71994. BABYLON.serialize()
  71995. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  71996. return FreeCameraTouchInput;
  71997. }());
  71998. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  71999. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  72000. })(BABYLON || (BABYLON = {}));
  72001. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  72002. var BABYLON;
  72003. (function (BABYLON) {
  72004. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  72005. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  72006. });
  72007. // We're mainly based on the logic defined into the FreeCamera code
  72008. var TouchCamera = /** @class */ (function (_super) {
  72009. __extends(TouchCamera, _super);
  72010. //-- end properties for backward compatibility for inputs
  72011. function TouchCamera(name, position, scene) {
  72012. var _this = _super.call(this, name, position, scene) || this;
  72013. _this.inputs.addTouch();
  72014. _this._setupInputs();
  72015. return _this;
  72016. }
  72017. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  72018. //-- Begin properties for backward compatibility for inputs
  72019. get: function () {
  72020. var touch = this.inputs.attached["touch"];
  72021. if (touch)
  72022. return touch.touchAngularSensibility;
  72023. return 0;
  72024. },
  72025. set: function (value) {
  72026. var touch = this.inputs.attached["touch"];
  72027. if (touch)
  72028. touch.touchAngularSensibility = value;
  72029. },
  72030. enumerable: true,
  72031. configurable: true
  72032. });
  72033. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  72034. get: function () {
  72035. var touch = this.inputs.attached["touch"];
  72036. if (touch)
  72037. return touch.touchMoveSensibility;
  72038. return 0;
  72039. },
  72040. set: function (value) {
  72041. var touch = this.inputs.attached["touch"];
  72042. if (touch)
  72043. touch.touchMoveSensibility = value;
  72044. },
  72045. enumerable: true,
  72046. configurable: true
  72047. });
  72048. TouchCamera.prototype.getClassName = function () {
  72049. return "TouchCamera";
  72050. };
  72051. TouchCamera.prototype._setupInputs = function () {
  72052. var mouse = this.inputs.attached["mouse"];
  72053. if (mouse) {
  72054. mouse.touchEnabled = false;
  72055. }
  72056. };
  72057. return TouchCamera;
  72058. }(BABYLON.FreeCamera));
  72059. BABYLON.TouchCamera = TouchCamera;
  72060. })(BABYLON || (BABYLON = {}));
  72061. //# sourceMappingURL=babylon.touchCamera.js.map
  72062. var BABYLON;
  72063. (function (BABYLON) {
  72064. var ProceduralTexture = /** @class */ (function (_super) {
  72065. __extends(ProceduralTexture, _super);
  72066. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  72067. if (fallbackTexture === void 0) { fallbackTexture = null; }
  72068. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72069. if (isCube === void 0) { isCube = false; }
  72070. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72071. _this.isCube = isCube;
  72072. _this.isEnabled = true;
  72073. _this._currentRefreshId = -1;
  72074. _this._refreshRate = 1;
  72075. _this._vertexBuffers = {};
  72076. _this._uniforms = new Array();
  72077. _this._samplers = new Array();
  72078. _this._textures = {};
  72079. _this._floats = {};
  72080. _this._ints = {};
  72081. _this._floatsArrays = {};
  72082. _this._colors3 = {};
  72083. _this._colors4 = {};
  72084. _this._vectors2 = {};
  72085. _this._vectors3 = {};
  72086. _this._matrices = {};
  72087. _this._fallbackTextureUsed = false;
  72088. scene = _this.getScene();
  72089. scene.proceduralTextures.push(_this);
  72090. _this._engine = scene.getEngine();
  72091. _this.name = name;
  72092. _this.isRenderTarget = true;
  72093. _this._size = size;
  72094. _this._generateMipMaps = generateMipMaps;
  72095. _this.setFragment(fragment);
  72096. _this._fallbackTexture = fallbackTexture;
  72097. if (isCube) {
  72098. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  72099. _this.setFloat("face", 0);
  72100. }
  72101. else {
  72102. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  72103. }
  72104. // VBO
  72105. var vertices = [];
  72106. vertices.push(1, 1);
  72107. vertices.push(-1, 1);
  72108. vertices.push(-1, -1);
  72109. vertices.push(1, -1);
  72110. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72111. _this._createIndexBuffer();
  72112. return _this;
  72113. }
  72114. ProceduralTexture.prototype._createIndexBuffer = function () {
  72115. var engine = this._engine;
  72116. // Indices
  72117. var indices = [];
  72118. indices.push(0);
  72119. indices.push(1);
  72120. indices.push(2);
  72121. indices.push(0);
  72122. indices.push(2);
  72123. indices.push(3);
  72124. this._indexBuffer = engine.createIndexBuffer(indices);
  72125. };
  72126. ProceduralTexture.prototype._rebuild = function () {
  72127. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72128. if (vb) {
  72129. vb._rebuild();
  72130. }
  72131. this._createIndexBuffer();
  72132. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72133. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72134. }
  72135. };
  72136. ProceduralTexture.prototype.reset = function () {
  72137. if (this._effect === undefined) {
  72138. return;
  72139. }
  72140. var engine = this._engine;
  72141. engine._releaseEffect(this._effect);
  72142. };
  72143. ProceduralTexture.prototype.isReady = function () {
  72144. var _this = this;
  72145. var engine = this._engine;
  72146. var shaders;
  72147. if (!this._fragment) {
  72148. return false;
  72149. }
  72150. if (this._fallbackTextureUsed) {
  72151. return true;
  72152. }
  72153. if (this._fragment.fragmentElement !== undefined) {
  72154. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  72155. }
  72156. else {
  72157. shaders = { vertex: "procedural", fragment: this._fragment };
  72158. }
  72159. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  72160. _this.releaseInternalTexture();
  72161. if (_this._fallbackTexture) {
  72162. _this._texture = _this._fallbackTexture._texture;
  72163. if (_this._texture) {
  72164. _this._texture.incrementReferences();
  72165. }
  72166. }
  72167. _this._fallbackTextureUsed = true;
  72168. });
  72169. return this._effect.isReady();
  72170. };
  72171. ProceduralTexture.prototype.resetRefreshCounter = function () {
  72172. this._currentRefreshId = -1;
  72173. };
  72174. ProceduralTexture.prototype.setFragment = function (fragment) {
  72175. this._fragment = fragment;
  72176. };
  72177. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  72178. get: function () {
  72179. return this._refreshRate;
  72180. },
  72181. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72182. set: function (value) {
  72183. this._refreshRate = value;
  72184. this.resetRefreshCounter();
  72185. },
  72186. enumerable: true,
  72187. configurable: true
  72188. });
  72189. ProceduralTexture.prototype._shouldRender = function () {
  72190. if (!this.isEnabled || !this.isReady() || !this._texture) {
  72191. return false;
  72192. }
  72193. if (this._fallbackTextureUsed) {
  72194. return false;
  72195. }
  72196. if (this._currentRefreshId === -1) { // At least render once
  72197. this._currentRefreshId = 1;
  72198. return true;
  72199. }
  72200. if (this.refreshRate === this._currentRefreshId) {
  72201. this._currentRefreshId = 1;
  72202. return true;
  72203. }
  72204. this._currentRefreshId++;
  72205. return false;
  72206. };
  72207. ProceduralTexture.prototype.getRenderSize = function () {
  72208. return this._size;
  72209. };
  72210. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  72211. if (this._fallbackTextureUsed) {
  72212. return;
  72213. }
  72214. this.releaseInternalTexture();
  72215. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  72216. // Update properties
  72217. this._size = size;
  72218. this._generateMipMaps = generateMipMaps;
  72219. };
  72220. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  72221. if (this._uniforms.indexOf(uniformName) === -1) {
  72222. this._uniforms.push(uniformName);
  72223. }
  72224. };
  72225. ProceduralTexture.prototype.setTexture = function (name, texture) {
  72226. if (this._samplers.indexOf(name) === -1) {
  72227. this._samplers.push(name);
  72228. }
  72229. this._textures[name] = texture;
  72230. return this;
  72231. };
  72232. ProceduralTexture.prototype.setFloat = function (name, value) {
  72233. this._checkUniform(name);
  72234. this._floats[name] = value;
  72235. return this;
  72236. };
  72237. /**
  72238. * Set the value of an uniform to an integer value
  72239. * @param name defines the name of the uniform
  72240. * @param value defines the value to set
  72241. * @returns the current procedural texture
  72242. */
  72243. ProceduralTexture.prototype.setInt = function (name, value) {
  72244. this._checkUniform(name);
  72245. this._ints[name] = value;
  72246. return this;
  72247. };
  72248. ProceduralTexture.prototype.setFloats = function (name, value) {
  72249. this._checkUniform(name);
  72250. this._floatsArrays[name] = value;
  72251. return this;
  72252. };
  72253. ProceduralTexture.prototype.setColor3 = function (name, value) {
  72254. this._checkUniform(name);
  72255. this._colors3[name] = value;
  72256. return this;
  72257. };
  72258. ProceduralTexture.prototype.setColor4 = function (name, value) {
  72259. this._checkUniform(name);
  72260. this._colors4[name] = value;
  72261. return this;
  72262. };
  72263. ProceduralTexture.prototype.setVector2 = function (name, value) {
  72264. this._checkUniform(name);
  72265. this._vectors2[name] = value;
  72266. return this;
  72267. };
  72268. ProceduralTexture.prototype.setVector3 = function (name, value) {
  72269. this._checkUniform(name);
  72270. this._vectors3[name] = value;
  72271. return this;
  72272. };
  72273. ProceduralTexture.prototype.setMatrix = function (name, value) {
  72274. this._checkUniform(name);
  72275. this._matrices[name] = value;
  72276. return this;
  72277. };
  72278. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72279. var scene = this.getScene();
  72280. if (!scene) {
  72281. return;
  72282. }
  72283. var engine = this._engine;
  72284. // Render
  72285. engine.enableEffect(this._effect);
  72286. engine.setState(false);
  72287. // Texture
  72288. for (var name in this._textures) {
  72289. this._effect.setTexture(name, this._textures[name]);
  72290. }
  72291. // Float
  72292. for (name in this._ints) {
  72293. this._effect.setInt(name, this._ints[name]);
  72294. }
  72295. // Float
  72296. for (name in this._floats) {
  72297. this._effect.setFloat(name, this._floats[name]);
  72298. }
  72299. // Floats
  72300. for (name in this._floatsArrays) {
  72301. this._effect.setArray(name, this._floatsArrays[name]);
  72302. }
  72303. // Color3
  72304. for (name in this._colors3) {
  72305. this._effect.setColor3(name, this._colors3[name]);
  72306. }
  72307. // Color4
  72308. for (name in this._colors4) {
  72309. var color = this._colors4[name];
  72310. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  72311. }
  72312. // Vector2
  72313. for (name in this._vectors2) {
  72314. this._effect.setVector2(name, this._vectors2[name]);
  72315. }
  72316. // Vector3
  72317. for (name in this._vectors3) {
  72318. this._effect.setVector3(name, this._vectors3[name]);
  72319. }
  72320. // Matrix
  72321. for (name in this._matrices) {
  72322. this._effect.setMatrix(name, this._matrices[name]);
  72323. }
  72324. if (!this._texture) {
  72325. return;
  72326. }
  72327. if (this.isCube) {
  72328. for (var face = 0; face < 6; face++) {
  72329. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  72330. // VBOs
  72331. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72332. this._effect.setFloat("face", face);
  72333. // Clear
  72334. engine.clear(scene.clearColor, true, true, true);
  72335. // Draw order
  72336. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72337. // Mipmaps
  72338. if (face === 5) {
  72339. engine.generateMipMapsForCubemap(this._texture);
  72340. }
  72341. }
  72342. }
  72343. else {
  72344. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  72345. // VBOs
  72346. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72347. // Clear
  72348. engine.clear(scene.clearColor, true, true, true);
  72349. // Draw order
  72350. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72351. }
  72352. // Unbind
  72353. engine.unBindFramebuffer(this._texture, this.isCube);
  72354. if (this.onGenerated) {
  72355. this.onGenerated();
  72356. }
  72357. };
  72358. ProceduralTexture.prototype.clone = function () {
  72359. var textureSize = this.getSize();
  72360. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  72361. // Base texture
  72362. newTexture.hasAlpha = this.hasAlpha;
  72363. newTexture.level = this.level;
  72364. // RenderTarget Texture
  72365. newTexture.coordinatesMode = this.coordinatesMode;
  72366. return newTexture;
  72367. };
  72368. ProceduralTexture.prototype.dispose = function () {
  72369. var scene = this.getScene();
  72370. if (!scene) {
  72371. return;
  72372. }
  72373. var index = scene.proceduralTextures.indexOf(this);
  72374. if (index >= 0) {
  72375. scene.proceduralTextures.splice(index, 1);
  72376. }
  72377. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72378. if (vertexBuffer) {
  72379. vertexBuffer.dispose();
  72380. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72381. }
  72382. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  72383. this._indexBuffer = null;
  72384. }
  72385. _super.prototype.dispose.call(this);
  72386. };
  72387. __decorate([
  72388. BABYLON.serialize()
  72389. ], ProceduralTexture.prototype, "_size", void 0);
  72390. __decorate([
  72391. BABYLON.serialize()
  72392. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  72393. __decorate([
  72394. BABYLON.serialize()
  72395. ], ProceduralTexture.prototype, "isEnabled", void 0);
  72396. __decorate([
  72397. BABYLON.serialize()
  72398. ], ProceduralTexture.prototype, "refreshRate", null);
  72399. return ProceduralTexture;
  72400. }(BABYLON.Texture));
  72401. BABYLON.ProceduralTexture = ProceduralTexture;
  72402. })(BABYLON || (BABYLON = {}));
  72403. //# sourceMappingURL=babylon.proceduralTexture.js.map
  72404. var BABYLON;
  72405. (function (BABYLON) {
  72406. var CustomProceduralTexture = /** @class */ (function (_super) {
  72407. __extends(CustomProceduralTexture, _super);
  72408. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  72409. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  72410. _this._animate = true;
  72411. _this._time = 0;
  72412. _this._texturePath = texturePath;
  72413. //Try to load json
  72414. _this.loadJson(texturePath);
  72415. _this.refreshRate = 1;
  72416. return _this;
  72417. }
  72418. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  72419. var _this = this;
  72420. var noConfigFile = function () {
  72421. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  72422. try {
  72423. _this.setFragment(_this._texturePath);
  72424. }
  72425. catch (ex) {
  72426. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  72427. }
  72428. };
  72429. var configFileUrl = jsonUrl + "/config.json";
  72430. var xhr = new XMLHttpRequest();
  72431. xhr.open("GET", configFileUrl, true);
  72432. xhr.addEventListener("load", function () {
  72433. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72434. try {
  72435. _this._config = JSON.parse(xhr.response);
  72436. _this.updateShaderUniforms();
  72437. _this.updateTextures();
  72438. _this.setFragment(_this._texturePath + "/custom");
  72439. _this._animate = _this._config.animate;
  72440. _this.refreshRate = _this._config.refreshrate;
  72441. }
  72442. catch (ex) {
  72443. noConfigFile();
  72444. }
  72445. }
  72446. else {
  72447. noConfigFile();
  72448. }
  72449. }, false);
  72450. xhr.addEventListener("error", function () {
  72451. noConfigFile();
  72452. }, false);
  72453. try {
  72454. xhr.send();
  72455. }
  72456. catch (ex) {
  72457. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  72458. }
  72459. };
  72460. CustomProceduralTexture.prototype.isReady = function () {
  72461. if (!_super.prototype.isReady.call(this)) {
  72462. return false;
  72463. }
  72464. for (var name in this._textures) {
  72465. var texture = this._textures[name];
  72466. if (!texture.isReady()) {
  72467. return false;
  72468. }
  72469. }
  72470. return true;
  72471. };
  72472. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72473. var scene = this.getScene();
  72474. if (this._animate && scene) {
  72475. this._time += scene.getAnimationRatio() * 0.03;
  72476. this.updateShaderUniforms();
  72477. }
  72478. _super.prototype.render.call(this, useCameraPostProcess);
  72479. };
  72480. CustomProceduralTexture.prototype.updateTextures = function () {
  72481. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  72482. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  72483. }
  72484. };
  72485. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  72486. if (this._config) {
  72487. for (var j = 0; j < this._config.uniforms.length; j++) {
  72488. var uniform = this._config.uniforms[j];
  72489. switch (uniform.type) {
  72490. case "float":
  72491. this.setFloat(uniform.name, uniform.value);
  72492. break;
  72493. case "color3":
  72494. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  72495. break;
  72496. case "color4":
  72497. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  72498. break;
  72499. case "vector2":
  72500. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  72501. break;
  72502. case "vector3":
  72503. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  72504. break;
  72505. }
  72506. }
  72507. }
  72508. this.setFloat("time", this._time);
  72509. };
  72510. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  72511. get: function () {
  72512. return this._animate;
  72513. },
  72514. set: function (value) {
  72515. this._animate = value;
  72516. },
  72517. enumerable: true,
  72518. configurable: true
  72519. });
  72520. return CustomProceduralTexture;
  72521. }(BABYLON.ProceduralTexture));
  72522. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  72523. })(BABYLON || (BABYLON = {}));
  72524. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  72525. var BABYLON;
  72526. (function (BABYLON) {
  72527. var FreeCameraGamepadInput = /** @class */ (function () {
  72528. function FreeCameraGamepadInput() {
  72529. this.gamepadAngularSensibility = 200;
  72530. this.gamepadMoveSensibility = 40;
  72531. // private members
  72532. this._cameraTransform = BABYLON.Matrix.Identity();
  72533. this._deltaTransform = BABYLON.Vector3.Zero();
  72534. this._vector3 = BABYLON.Vector3.Zero();
  72535. this._vector2 = BABYLON.Vector2.Zero();
  72536. }
  72537. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72538. var _this = this;
  72539. var manager = this.camera.getScene().gamepadManager;
  72540. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72541. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72542. // prioritize XBOX gamepads.
  72543. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72544. _this.gamepad = gamepad;
  72545. }
  72546. }
  72547. });
  72548. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72549. if (_this.gamepad === gamepad) {
  72550. _this.gamepad = null;
  72551. }
  72552. });
  72553. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72554. };
  72555. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  72556. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72557. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72558. this.gamepad = null;
  72559. };
  72560. FreeCameraGamepadInput.prototype.checkInputs = function () {
  72561. if (this.gamepad && this.gamepad.leftStick) {
  72562. var camera = this.camera;
  72563. var LSValues = this.gamepad.leftStick;
  72564. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  72565. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72566. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  72567. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  72568. var RSValues = this.gamepad.rightStick;
  72569. if (RSValues) {
  72570. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  72571. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  72572. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  72573. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  72574. }
  72575. else {
  72576. RSValues = { x: 0, y: 0 };
  72577. }
  72578. if (!camera.rotationQuaternion) {
  72579. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  72580. }
  72581. else {
  72582. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  72583. }
  72584. var speed = camera._computeLocalCameraSpeed() * 50.0;
  72585. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  72586. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  72587. camera.cameraDirection.addInPlace(this._deltaTransform);
  72588. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  72589. camera.cameraRotation.addInPlace(this._vector2);
  72590. }
  72591. };
  72592. FreeCameraGamepadInput.prototype.getClassName = function () {
  72593. return "FreeCameraGamepadInput";
  72594. };
  72595. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  72596. return "gamepad";
  72597. };
  72598. __decorate([
  72599. BABYLON.serialize()
  72600. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  72601. __decorate([
  72602. BABYLON.serialize()
  72603. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72604. return FreeCameraGamepadInput;
  72605. }());
  72606. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  72607. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  72608. })(BABYLON || (BABYLON = {}));
  72609. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  72610. var BABYLON;
  72611. (function (BABYLON) {
  72612. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  72613. function ArcRotateCameraGamepadInput() {
  72614. this.gamepadRotationSensibility = 80;
  72615. this.gamepadMoveSensibility = 40;
  72616. }
  72617. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72618. var _this = this;
  72619. var manager = this.camera.getScene().gamepadManager;
  72620. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72621. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72622. // prioritize XBOX gamepads.
  72623. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72624. _this.gamepad = gamepad;
  72625. }
  72626. }
  72627. });
  72628. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72629. if (_this.gamepad === gamepad) {
  72630. _this.gamepad = null;
  72631. }
  72632. });
  72633. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72634. };
  72635. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  72636. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72637. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72638. this.gamepad = null;
  72639. };
  72640. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  72641. if (this.gamepad) {
  72642. var camera = this.camera;
  72643. var RSValues = this.gamepad.rightStick;
  72644. if (RSValues) {
  72645. if (RSValues.x != 0) {
  72646. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  72647. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  72648. camera.inertialAlphaOffset += normalizedRX;
  72649. }
  72650. }
  72651. if (RSValues.y != 0) {
  72652. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  72653. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  72654. camera.inertialBetaOffset += normalizedRY;
  72655. }
  72656. }
  72657. }
  72658. var LSValues = this.gamepad.leftStick;
  72659. if (LSValues && LSValues.y != 0) {
  72660. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72661. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  72662. this.camera.inertialRadiusOffset -= normalizedLY;
  72663. }
  72664. }
  72665. }
  72666. };
  72667. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  72668. return "ArcRotateCameraGamepadInput";
  72669. };
  72670. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  72671. return "gamepad";
  72672. };
  72673. __decorate([
  72674. BABYLON.serialize()
  72675. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  72676. __decorate([
  72677. BABYLON.serialize()
  72678. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72679. return ArcRotateCameraGamepadInput;
  72680. }());
  72681. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  72682. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  72683. })(BABYLON || (BABYLON = {}));
  72684. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  72685. var BABYLON;
  72686. (function (BABYLON) {
  72687. var GamepadManager = /** @class */ (function () {
  72688. function GamepadManager(_scene) {
  72689. var _this = this;
  72690. this._scene = _scene;
  72691. this._babylonGamepads = [];
  72692. this._oneGamepadConnected = false;
  72693. this._isMonitoring = false;
  72694. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  72695. if (!BABYLON.Tools.IsWindowObjectExist()) {
  72696. this._gamepadEventSupported = false;
  72697. }
  72698. else {
  72699. this._gamepadEventSupported = 'GamepadEvent' in window;
  72700. this._gamepadSupport = (navigator.getGamepads ||
  72701. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  72702. }
  72703. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  72704. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  72705. for (var i in _this._babylonGamepads) {
  72706. var gamepad = _this._babylonGamepads[i];
  72707. if (gamepad && gamepad._isConnected) {
  72708. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  72709. }
  72710. }
  72711. });
  72712. this._onGamepadConnectedEvent = function (evt) {
  72713. var gamepad = evt.gamepad;
  72714. if (gamepad.index in _this._babylonGamepads) {
  72715. if (_this._babylonGamepads[gamepad.index].isConnected) {
  72716. return;
  72717. }
  72718. }
  72719. var newGamepad;
  72720. if (_this._babylonGamepads[gamepad.index]) {
  72721. newGamepad = _this._babylonGamepads[gamepad.index];
  72722. newGamepad.browserGamepad = gamepad;
  72723. newGamepad._isConnected = true;
  72724. }
  72725. else {
  72726. newGamepad = _this._addNewGamepad(gamepad);
  72727. }
  72728. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72729. _this._startMonitoringGamepads();
  72730. };
  72731. this._onGamepadDisconnectedEvent = function (evt) {
  72732. var gamepad = evt.gamepad;
  72733. // Remove the gamepad from the list of gamepads to monitor.
  72734. for (var i in _this._babylonGamepads) {
  72735. if (_this._babylonGamepads[i].index === gamepad.index) {
  72736. var disconnectedGamepad = _this._babylonGamepads[i];
  72737. disconnectedGamepad._isConnected = false;
  72738. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  72739. break;
  72740. }
  72741. }
  72742. };
  72743. if (this._gamepadSupport) {
  72744. //first add already-connected gamepads
  72745. this._updateGamepadObjects();
  72746. if (this._babylonGamepads.length) {
  72747. this._startMonitoringGamepads();
  72748. }
  72749. // Checking if the gamepad connected event is supported (like in Firefox)
  72750. if (this._gamepadEventSupported) {
  72751. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  72752. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  72753. }
  72754. else {
  72755. this._startMonitoringGamepads();
  72756. }
  72757. }
  72758. }
  72759. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  72760. get: function () {
  72761. return this._babylonGamepads;
  72762. },
  72763. enumerable: true,
  72764. configurable: true
  72765. });
  72766. GamepadManager.prototype.getGamepadByType = function (type) {
  72767. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  72768. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  72769. var gamepad = _a[_i];
  72770. if (gamepad && gamepad.type === type) {
  72771. return gamepad;
  72772. }
  72773. }
  72774. return null;
  72775. };
  72776. GamepadManager.prototype.dispose = function () {
  72777. if (this._gamepadEventSupported) {
  72778. if (this._onGamepadConnectedEvent) {
  72779. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  72780. }
  72781. if (this._onGamepadDisconnectedEvent) {
  72782. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  72783. }
  72784. this._onGamepadConnectedEvent = null;
  72785. this._onGamepadDisconnectedEvent = null;
  72786. }
  72787. this._babylonGamepads.forEach(function (gamepad) {
  72788. gamepad.dispose();
  72789. });
  72790. this.onGamepadConnectedObservable.clear();
  72791. this.onGamepadDisconnectedObservable.clear();
  72792. this._oneGamepadConnected = false;
  72793. this._stopMonitoringGamepads();
  72794. this._babylonGamepads = [];
  72795. };
  72796. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  72797. if (!this._oneGamepadConnected) {
  72798. this._oneGamepadConnected = true;
  72799. }
  72800. var newGamepad;
  72801. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  72802. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  72803. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  72804. }
  72805. // if pose is supported, use the (WebVR) pose enabled controller
  72806. else if (gamepad.pose) {
  72807. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  72808. }
  72809. else {
  72810. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  72811. }
  72812. this._babylonGamepads[newGamepad.index] = newGamepad;
  72813. return newGamepad;
  72814. };
  72815. GamepadManager.prototype._startMonitoringGamepads = function () {
  72816. if (!this._isMonitoring) {
  72817. this._isMonitoring = true;
  72818. //back-comp
  72819. if (!this._scene) {
  72820. this._checkGamepadsStatus();
  72821. }
  72822. }
  72823. };
  72824. GamepadManager.prototype._stopMonitoringGamepads = function () {
  72825. this._isMonitoring = false;
  72826. };
  72827. GamepadManager.prototype._checkGamepadsStatus = function () {
  72828. var _this = this;
  72829. // Hack to be compatible Chrome
  72830. this._updateGamepadObjects();
  72831. for (var i in this._babylonGamepads) {
  72832. var gamepad = this._babylonGamepads[i];
  72833. if (!gamepad || !gamepad.isConnected) {
  72834. continue;
  72835. }
  72836. gamepad.update();
  72837. }
  72838. if (this._isMonitoring && !this._scene) {
  72839. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  72840. }
  72841. };
  72842. // This function is called only on Chrome, which does not properly support
  72843. // connection/disconnection events and forces you to recopy again the gamepad object
  72844. GamepadManager.prototype._updateGamepadObjects = function () {
  72845. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  72846. for (var i = 0; i < gamepads.length; i++) {
  72847. var gamepad = gamepads[i];
  72848. if (gamepad) {
  72849. if (!this._babylonGamepads[gamepad.index]) {
  72850. var newGamepad = this._addNewGamepad(gamepad);
  72851. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72852. }
  72853. else {
  72854. // Forced to copy again this object for Chrome for unknown reason
  72855. this._babylonGamepads[i].browserGamepad = gamepad;
  72856. if (!this._babylonGamepads[i].isConnected) {
  72857. this._babylonGamepads[i]._isConnected = true;
  72858. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  72859. }
  72860. }
  72861. }
  72862. }
  72863. };
  72864. return GamepadManager;
  72865. }());
  72866. BABYLON.GamepadManager = GamepadManager;
  72867. })(BABYLON || (BABYLON = {}));
  72868. //# sourceMappingURL=babylon.gamepadManager.js.map
  72869. var BABYLON;
  72870. (function (BABYLON) {
  72871. var StickValues = /** @class */ (function () {
  72872. function StickValues(x, y) {
  72873. this.x = x;
  72874. this.y = y;
  72875. }
  72876. return StickValues;
  72877. }());
  72878. BABYLON.StickValues = StickValues;
  72879. var Gamepad = /** @class */ (function () {
  72880. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  72881. if (leftStickX === void 0) { leftStickX = 0; }
  72882. if (leftStickY === void 0) { leftStickY = 1; }
  72883. if (rightStickX === void 0) { rightStickX = 2; }
  72884. if (rightStickY === void 0) { rightStickY = 3; }
  72885. this.id = id;
  72886. this.index = index;
  72887. this.browserGamepad = browserGamepad;
  72888. this._isConnected = true;
  72889. this._invertLeftStickY = false;
  72890. this.type = Gamepad.GAMEPAD;
  72891. this._leftStickAxisX = leftStickX;
  72892. this._leftStickAxisY = leftStickY;
  72893. this._rightStickAxisX = rightStickX;
  72894. this._rightStickAxisY = rightStickY;
  72895. if (this.browserGamepad.axes.length >= 2) {
  72896. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72897. }
  72898. if (this.browserGamepad.axes.length >= 4) {
  72899. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72900. }
  72901. }
  72902. Object.defineProperty(Gamepad.prototype, "isConnected", {
  72903. get: function () {
  72904. return this._isConnected;
  72905. },
  72906. enumerable: true,
  72907. configurable: true
  72908. });
  72909. Gamepad.prototype.onleftstickchanged = function (callback) {
  72910. this._onleftstickchanged = callback;
  72911. };
  72912. Gamepad.prototype.onrightstickchanged = function (callback) {
  72913. this._onrightstickchanged = callback;
  72914. };
  72915. Object.defineProperty(Gamepad.prototype, "leftStick", {
  72916. get: function () {
  72917. return this._leftStick;
  72918. },
  72919. set: function (newValues) {
  72920. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  72921. this._onleftstickchanged(newValues);
  72922. }
  72923. this._leftStick = newValues;
  72924. },
  72925. enumerable: true,
  72926. configurable: true
  72927. });
  72928. Object.defineProperty(Gamepad.prototype, "rightStick", {
  72929. get: function () {
  72930. return this._rightStick;
  72931. },
  72932. set: function (newValues) {
  72933. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  72934. this._onrightstickchanged(newValues);
  72935. }
  72936. this._rightStick = newValues;
  72937. },
  72938. enumerable: true,
  72939. configurable: true
  72940. });
  72941. Gamepad.prototype.update = function () {
  72942. if (this._leftStick) {
  72943. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72944. if (this._invertLeftStickY) {
  72945. this.leftStick.y *= -1;
  72946. }
  72947. }
  72948. if (this._rightStick) {
  72949. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72950. }
  72951. };
  72952. Gamepad.prototype.dispose = function () {
  72953. };
  72954. Gamepad.GAMEPAD = 0;
  72955. Gamepad.GENERIC = 1;
  72956. Gamepad.XBOX = 2;
  72957. Gamepad.POSE_ENABLED = 3;
  72958. return Gamepad;
  72959. }());
  72960. BABYLON.Gamepad = Gamepad;
  72961. var GenericPad = /** @class */ (function (_super) {
  72962. __extends(GenericPad, _super);
  72963. function GenericPad(id, index, browserGamepad) {
  72964. var _this = _super.call(this, id, index, browserGamepad) || this;
  72965. _this.onButtonDownObservable = new BABYLON.Observable();
  72966. _this.onButtonUpObservable = new BABYLON.Observable();
  72967. _this.type = Gamepad.GENERIC;
  72968. _this._buttons = new Array(browserGamepad.buttons.length);
  72969. return _this;
  72970. }
  72971. GenericPad.prototype.onbuttondown = function (callback) {
  72972. this._onbuttondown = callback;
  72973. };
  72974. GenericPad.prototype.onbuttonup = function (callback) {
  72975. this._onbuttonup = callback;
  72976. };
  72977. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  72978. if (newValue !== currentValue) {
  72979. if (newValue === 1) {
  72980. if (this._onbuttondown) {
  72981. this._onbuttondown(buttonIndex);
  72982. }
  72983. this.onButtonDownObservable.notifyObservers(buttonIndex);
  72984. }
  72985. if (newValue === 0) {
  72986. if (this._onbuttonup) {
  72987. this._onbuttonup(buttonIndex);
  72988. }
  72989. this.onButtonUpObservable.notifyObservers(buttonIndex);
  72990. }
  72991. }
  72992. return newValue;
  72993. };
  72994. GenericPad.prototype.update = function () {
  72995. _super.prototype.update.call(this);
  72996. for (var index = 0; index < this._buttons.length; index++) {
  72997. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  72998. }
  72999. };
  73000. GenericPad.prototype.dispose = function () {
  73001. _super.prototype.dispose.call(this);
  73002. this.onButtonDownObservable.clear();
  73003. this.onButtonUpObservable.clear();
  73004. };
  73005. return GenericPad;
  73006. }(Gamepad));
  73007. BABYLON.GenericPad = GenericPad;
  73008. })(BABYLON || (BABYLON = {}));
  73009. //# sourceMappingURL=babylon.gamepad.js.map
  73010. var BABYLON;
  73011. (function (BABYLON) {
  73012. /**
  73013. * Defines supported buttons for XBox360 compatible gamepads
  73014. */
  73015. var Xbox360Button;
  73016. (function (Xbox360Button) {
  73017. /** A */
  73018. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  73019. /** B */
  73020. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  73021. /** X */
  73022. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  73023. /** Y */
  73024. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  73025. /** Start */
  73026. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  73027. /** Back */
  73028. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  73029. /** Left button */
  73030. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  73031. /** Right button */
  73032. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  73033. /** Left stick */
  73034. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  73035. /** Right stick */
  73036. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  73037. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  73038. /** Defines values for XBox360 DPad */
  73039. var Xbox360Dpad;
  73040. (function (Xbox360Dpad) {
  73041. /** Up */
  73042. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  73043. /** Down */
  73044. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  73045. /** Left */
  73046. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  73047. /** Right */
  73048. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  73049. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  73050. /**
  73051. * Defines a XBox360 gamepad
  73052. */
  73053. var Xbox360Pad = /** @class */ (function (_super) {
  73054. __extends(Xbox360Pad, _super);
  73055. /**
  73056. * Creates a new XBox360 gamepad object
  73057. * @param id defines the id of this gamepad
  73058. * @param index defines its index
  73059. * @param gamepad defines the internal HTML gamepad object
  73060. * @param xboxOne defines if it is a XBox One gamepad
  73061. */
  73062. function Xbox360Pad(id, index, gamepad, xboxOne) {
  73063. if (xboxOne === void 0) { xboxOne = false; }
  73064. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  73065. _this._leftTrigger = 0;
  73066. _this._rightTrigger = 0;
  73067. /** Observable raised when a button is pressed */
  73068. _this.onButtonDownObservable = new BABYLON.Observable();
  73069. /** Observable raised when a button is released */
  73070. _this.onButtonUpObservable = new BABYLON.Observable();
  73071. /** Observable raised when a pad is pressed */
  73072. _this.onPadDownObservable = new BABYLON.Observable();
  73073. /** Observable raised when a pad is released */
  73074. _this.onPadUpObservable = new BABYLON.Observable();
  73075. _this._buttonA = 0;
  73076. _this._buttonB = 0;
  73077. _this._buttonX = 0;
  73078. _this._buttonY = 0;
  73079. _this._buttonBack = 0;
  73080. _this._buttonStart = 0;
  73081. _this._buttonLB = 0;
  73082. _this._buttonRB = 0;
  73083. _this._buttonLeftStick = 0;
  73084. _this._buttonRightStick = 0;
  73085. _this._dPadUp = 0;
  73086. _this._dPadDown = 0;
  73087. _this._dPadLeft = 0;
  73088. _this._dPadRight = 0;
  73089. _this._isXboxOnePad = false;
  73090. _this.type = BABYLON.Gamepad.XBOX;
  73091. _this._isXboxOnePad = xboxOne;
  73092. return _this;
  73093. }
  73094. /**
  73095. * Defines the callback to call when left trigger is pressed
  73096. * @param callback defines the callback to use
  73097. */
  73098. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  73099. this._onlefttriggerchanged = callback;
  73100. };
  73101. /**
  73102. * Defines the callback to call when right trigger is pressed
  73103. * @param callback defines the callback to use
  73104. */
  73105. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  73106. this._onrighttriggerchanged = callback;
  73107. };
  73108. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  73109. /**
  73110. * Gets or sets left trigger value
  73111. */
  73112. get: function () {
  73113. return this._leftTrigger;
  73114. },
  73115. set: function (newValue) {
  73116. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  73117. this._onlefttriggerchanged(newValue);
  73118. }
  73119. this._leftTrigger = newValue;
  73120. },
  73121. enumerable: true,
  73122. configurable: true
  73123. });
  73124. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  73125. /**
  73126. * Gets or sets right trigger value
  73127. */
  73128. get: function () {
  73129. return this._rightTrigger;
  73130. },
  73131. set: function (newValue) {
  73132. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  73133. this._onrighttriggerchanged(newValue);
  73134. }
  73135. this._rightTrigger = newValue;
  73136. },
  73137. enumerable: true,
  73138. configurable: true
  73139. });
  73140. /**
  73141. * Defines the callback to call when a button is pressed
  73142. * @param callback defines the callback to use
  73143. */
  73144. Xbox360Pad.prototype.onbuttondown = function (callback) {
  73145. this._onbuttondown = callback;
  73146. };
  73147. /**
  73148. * Defines the callback to call when a button is released
  73149. * @param callback defines the callback to use
  73150. */
  73151. Xbox360Pad.prototype.onbuttonup = function (callback) {
  73152. this._onbuttonup = callback;
  73153. };
  73154. /**
  73155. * Defines the callback to call when a pad is pressed
  73156. * @param callback defines the callback to use
  73157. */
  73158. Xbox360Pad.prototype.ondpaddown = function (callback) {
  73159. this._ondpaddown = callback;
  73160. };
  73161. /**
  73162. * Defines the callback to call when a pad is released
  73163. * @param callback defines the callback to use
  73164. */
  73165. Xbox360Pad.prototype.ondpadup = function (callback) {
  73166. this._ondpadup = callback;
  73167. };
  73168. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  73169. if (newValue !== currentValue) {
  73170. if (newValue === 1) {
  73171. if (this._onbuttondown) {
  73172. this._onbuttondown(buttonType);
  73173. }
  73174. this.onButtonDownObservable.notifyObservers(buttonType);
  73175. }
  73176. if (newValue === 0) {
  73177. if (this._onbuttonup) {
  73178. this._onbuttonup(buttonType);
  73179. }
  73180. this.onButtonUpObservable.notifyObservers(buttonType);
  73181. }
  73182. }
  73183. return newValue;
  73184. };
  73185. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  73186. if (newValue !== currentValue) {
  73187. if (newValue === 1) {
  73188. if (this._ondpaddown) {
  73189. this._ondpaddown(buttonType);
  73190. }
  73191. this.onPadDownObservable.notifyObservers(buttonType);
  73192. }
  73193. if (newValue === 0) {
  73194. if (this._ondpadup) {
  73195. this._ondpadup(buttonType);
  73196. }
  73197. this.onPadUpObservable.notifyObservers(buttonType);
  73198. }
  73199. }
  73200. return newValue;
  73201. };
  73202. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  73203. /** Gets or sets value of A button */
  73204. get: function () {
  73205. return this._buttonA;
  73206. },
  73207. set: function (value) {
  73208. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  73209. },
  73210. enumerable: true,
  73211. configurable: true
  73212. });
  73213. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  73214. /** Gets or sets value of B button */
  73215. get: function () {
  73216. return this._buttonB;
  73217. },
  73218. set: function (value) {
  73219. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  73220. },
  73221. enumerable: true,
  73222. configurable: true
  73223. });
  73224. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  73225. /** Gets or sets value of X button */
  73226. get: function () {
  73227. return this._buttonX;
  73228. },
  73229. set: function (value) {
  73230. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  73231. },
  73232. enumerable: true,
  73233. configurable: true
  73234. });
  73235. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  73236. /** Gets or sets value of Y button */
  73237. get: function () {
  73238. return this._buttonY;
  73239. },
  73240. set: function (value) {
  73241. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  73242. },
  73243. enumerable: true,
  73244. configurable: true
  73245. });
  73246. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  73247. /** Gets or sets value of Start button */
  73248. get: function () {
  73249. return this._buttonStart;
  73250. },
  73251. set: function (value) {
  73252. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  73253. },
  73254. enumerable: true,
  73255. configurable: true
  73256. });
  73257. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  73258. /** Gets or sets value of Back button */
  73259. get: function () {
  73260. return this._buttonBack;
  73261. },
  73262. set: function (value) {
  73263. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  73264. },
  73265. enumerable: true,
  73266. configurable: true
  73267. });
  73268. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  73269. /** Gets or sets value of Left button */
  73270. get: function () {
  73271. return this._buttonLB;
  73272. },
  73273. set: function (value) {
  73274. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  73275. },
  73276. enumerable: true,
  73277. configurable: true
  73278. });
  73279. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  73280. /** Gets or sets value of Right button */
  73281. get: function () {
  73282. return this._buttonRB;
  73283. },
  73284. set: function (value) {
  73285. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  73286. },
  73287. enumerable: true,
  73288. configurable: true
  73289. });
  73290. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  73291. /** Gets or sets value of left stick */
  73292. get: function () {
  73293. return this._buttonLeftStick;
  73294. },
  73295. set: function (value) {
  73296. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  73297. },
  73298. enumerable: true,
  73299. configurable: true
  73300. });
  73301. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  73302. /** Gets or sets value of right stick */
  73303. get: function () {
  73304. return this._buttonRightStick;
  73305. },
  73306. set: function (value) {
  73307. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  73308. },
  73309. enumerable: true,
  73310. configurable: true
  73311. });
  73312. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  73313. /** Gets or sets value of DPad up */
  73314. get: function () {
  73315. return this._dPadUp;
  73316. },
  73317. set: function (value) {
  73318. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  73319. },
  73320. enumerable: true,
  73321. configurable: true
  73322. });
  73323. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  73324. /** Gets or sets value of DPad down */
  73325. get: function () {
  73326. return this._dPadDown;
  73327. },
  73328. set: function (value) {
  73329. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  73330. },
  73331. enumerable: true,
  73332. configurable: true
  73333. });
  73334. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  73335. /** Gets or sets value of DPad left */
  73336. get: function () {
  73337. return this._dPadLeft;
  73338. },
  73339. set: function (value) {
  73340. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  73341. },
  73342. enumerable: true,
  73343. configurable: true
  73344. });
  73345. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  73346. /** Gets or sets value of DPad right */
  73347. get: function () {
  73348. return this._dPadRight;
  73349. },
  73350. set: function (value) {
  73351. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  73352. },
  73353. enumerable: true,
  73354. configurable: true
  73355. });
  73356. /**
  73357. * Force the gamepad to synchronize with device values
  73358. */
  73359. Xbox360Pad.prototype.update = function () {
  73360. _super.prototype.update.call(this);
  73361. if (this._isXboxOnePad) {
  73362. this.buttonA = this.browserGamepad.buttons[0].value;
  73363. this.buttonB = this.browserGamepad.buttons[1].value;
  73364. this.buttonX = this.browserGamepad.buttons[2].value;
  73365. this.buttonY = this.browserGamepad.buttons[3].value;
  73366. this.buttonLB = this.browserGamepad.buttons[4].value;
  73367. this.buttonRB = this.browserGamepad.buttons[5].value;
  73368. this.leftTrigger = this.browserGamepad.axes[2];
  73369. this.rightTrigger = this.browserGamepad.axes[5];
  73370. this.buttonBack = this.browserGamepad.buttons[9].value;
  73371. this.buttonStart = this.browserGamepad.buttons[8].value;
  73372. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  73373. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  73374. this.dPadUp = this.browserGamepad.buttons[11].value;
  73375. this.dPadDown = this.browserGamepad.buttons[12].value;
  73376. this.dPadLeft = this.browserGamepad.buttons[13].value;
  73377. this.dPadRight = this.browserGamepad.buttons[14].value;
  73378. }
  73379. else {
  73380. this.buttonA = this.browserGamepad.buttons[0].value;
  73381. this.buttonB = this.browserGamepad.buttons[1].value;
  73382. this.buttonX = this.browserGamepad.buttons[2].value;
  73383. this.buttonY = this.browserGamepad.buttons[3].value;
  73384. this.buttonLB = this.browserGamepad.buttons[4].value;
  73385. this.buttonRB = this.browserGamepad.buttons[5].value;
  73386. this.leftTrigger = this.browserGamepad.buttons[6].value;
  73387. this.rightTrigger = this.browserGamepad.buttons[7].value;
  73388. this.buttonBack = this.browserGamepad.buttons[8].value;
  73389. this.buttonStart = this.browserGamepad.buttons[9].value;
  73390. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  73391. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  73392. this.dPadUp = this.browserGamepad.buttons[12].value;
  73393. this.dPadDown = this.browserGamepad.buttons[13].value;
  73394. this.dPadLeft = this.browserGamepad.buttons[14].value;
  73395. this.dPadRight = this.browserGamepad.buttons[15].value;
  73396. }
  73397. };
  73398. Xbox360Pad.prototype.dispose = function () {
  73399. _super.prototype.dispose.call(this);
  73400. this.onButtonDownObservable.clear();
  73401. this.onButtonUpObservable.clear();
  73402. this.onPadDownObservable.clear();
  73403. this.onPadUpObservable.clear();
  73404. };
  73405. return Xbox360Pad;
  73406. }(BABYLON.Gamepad));
  73407. BABYLON.Xbox360Pad = Xbox360Pad;
  73408. })(BABYLON || (BABYLON = {}));
  73409. //# sourceMappingURL=babylon.xboxGamepad.js.map
  73410. var BABYLON;
  73411. (function (BABYLON) {
  73412. /**
  73413. * Defines the types of pose enabled controllers that are supported
  73414. */
  73415. var PoseEnabledControllerType;
  73416. (function (PoseEnabledControllerType) {
  73417. /**
  73418. * HTC Vive
  73419. */
  73420. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  73421. /**
  73422. * Oculus Rift
  73423. */
  73424. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  73425. /**
  73426. * Windows mixed reality
  73427. */
  73428. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  73429. /**
  73430. * Samsung gear VR
  73431. */
  73432. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  73433. /**
  73434. * Google Daydream
  73435. */
  73436. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  73437. /**
  73438. * Generic
  73439. */
  73440. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  73441. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  73442. /**
  73443. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  73444. */
  73445. var PoseEnabledControllerHelper = /** @class */ (function () {
  73446. function PoseEnabledControllerHelper() {
  73447. }
  73448. /**
  73449. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  73450. * @param vrGamepad the gamepad to initialized
  73451. * @returns a vr controller of the type the gamepad identified as
  73452. */
  73453. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  73454. // Oculus Touch
  73455. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  73456. return new BABYLON.OculusTouchController(vrGamepad);
  73457. }
  73458. // Windows Mixed Reality controllers
  73459. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  73460. return new BABYLON.WindowsMotionController(vrGamepad);
  73461. }
  73462. // HTC Vive
  73463. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  73464. return new BABYLON.ViveController(vrGamepad);
  73465. }
  73466. // Samsung/Oculus Gear VR or Oculus Go
  73467. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  73468. return new BABYLON.GearVRController(vrGamepad);
  73469. }
  73470. // Google Daydream
  73471. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  73472. return new BABYLON.DaydreamController(vrGamepad);
  73473. }
  73474. // Generic
  73475. else {
  73476. return new BABYLON.GenericController(vrGamepad);
  73477. }
  73478. };
  73479. return PoseEnabledControllerHelper;
  73480. }());
  73481. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  73482. /**
  73483. * Defines the PoseEnabledController object that contains state of a vr capable controller
  73484. */
  73485. var PoseEnabledController = /** @class */ (function (_super) {
  73486. __extends(PoseEnabledController, _super);
  73487. /**
  73488. * Creates a new PoseEnabledController from a gamepad
  73489. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  73490. */
  73491. function PoseEnabledController(browserGamepad) {
  73492. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  73493. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  73494. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  73495. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  73496. /**
  73497. * The device position in babylon space
  73498. */
  73499. _this.devicePosition = BABYLON.Vector3.Zero();
  73500. /**
  73501. * The device rotation in babylon space
  73502. */
  73503. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  73504. /**
  73505. * The scale factor of the device in babylon space
  73506. */
  73507. _this.deviceScaleFactor = 1;
  73508. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  73509. /**
  73510. * Internal, matrix used to convert room space to babylon space
  73511. */
  73512. _this._deviceToWorld = BABYLON.Matrix.Identity();
  73513. /**
  73514. * Node to be used when casting a ray from the controller
  73515. */
  73516. _this._pointingPoseNode = null;
  73517. _this._workingMatrix = BABYLON.Matrix.Identity();
  73518. /**
  73519. * @hidden
  73520. */
  73521. _this._meshAttachedObservable = new BABYLON.Observable();
  73522. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  73523. _this.controllerType = PoseEnabledControllerType.GENERIC;
  73524. _this.position = BABYLON.Vector3.Zero();
  73525. _this.rotationQuaternion = new BABYLON.Quaternion();
  73526. _this._calculatedPosition = BABYLON.Vector3.Zero();
  73527. _this._calculatedRotation = new BABYLON.Quaternion();
  73528. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  73529. return _this;
  73530. }
  73531. /**
  73532. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  73533. */
  73534. PoseEnabledController.prototype.update = function () {
  73535. _super.prototype.update.call(this);
  73536. this._updatePoseAndMesh();
  73537. };
  73538. /**
  73539. * Updates only the pose device and mesh without doing any button event checking
  73540. */
  73541. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  73542. var pose = this.browserGamepad.pose;
  73543. this.updateFromDevice(pose);
  73544. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  73545. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  73546. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  73547. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  73548. if (this._mesh) {
  73549. this._mesh.position.copyFrom(this.devicePosition);
  73550. if (this._mesh.rotationQuaternion) {
  73551. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  73552. }
  73553. }
  73554. };
  73555. /**
  73556. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  73557. * @param poseData raw pose fromthe device
  73558. */
  73559. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  73560. if (poseData) {
  73561. this.rawPose = poseData;
  73562. if (poseData.position) {
  73563. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  73564. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  73565. this._deviceRoomPosition.z *= -1;
  73566. }
  73567. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  73568. this._calculatedPosition.addInPlace(this.position);
  73569. }
  73570. var pose = this.rawPose;
  73571. if (poseData.orientation && pose.orientation) {
  73572. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  73573. if (this._mesh) {
  73574. if (this._mesh.getScene().useRightHandedSystem) {
  73575. this._deviceRoomRotationQuaternion.z *= -1;
  73576. this._deviceRoomRotationQuaternion.w *= -1;
  73577. }
  73578. else {
  73579. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  73580. }
  73581. }
  73582. // if the camera is set, rotate to the camera's rotation
  73583. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  73584. }
  73585. }
  73586. };
  73587. /**
  73588. * Attaches a mesh to the controller
  73589. * @param mesh the mesh to be attached
  73590. */
  73591. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  73592. if (this._mesh) {
  73593. this._mesh.parent = null;
  73594. }
  73595. this._mesh = mesh;
  73596. if (this._poseControlledCamera) {
  73597. this._mesh.parent = this._poseControlledCamera;
  73598. }
  73599. if (!this._mesh.rotationQuaternion) {
  73600. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  73601. }
  73602. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  73603. this._updatePoseAndMesh();
  73604. if (this._pointingPoseNode) {
  73605. var parents = [];
  73606. var obj = this._pointingPoseNode;
  73607. while (obj.parent) {
  73608. parents.push(obj.parent);
  73609. obj = obj.parent;
  73610. }
  73611. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  73612. }
  73613. this._meshAttachedObservable.notifyObservers(mesh);
  73614. };
  73615. /**
  73616. * Attaches the controllers mesh to a camera
  73617. * @param camera the camera the mesh should be attached to
  73618. */
  73619. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  73620. this._poseControlledCamera = camera;
  73621. if (this._mesh) {
  73622. this._mesh.parent = this._poseControlledCamera;
  73623. }
  73624. };
  73625. /**
  73626. * Disposes of the controller
  73627. */
  73628. PoseEnabledController.prototype.dispose = function () {
  73629. if (this._mesh) {
  73630. this._mesh.dispose();
  73631. }
  73632. this._mesh = null;
  73633. _super.prototype.dispose.call(this);
  73634. };
  73635. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  73636. /**
  73637. * The mesh that is attached to the controller
  73638. */
  73639. get: function () {
  73640. return this._mesh;
  73641. },
  73642. enumerable: true,
  73643. configurable: true
  73644. });
  73645. /**
  73646. * Gets the ray of the controller in the direction the controller is pointing
  73647. * @param length the length the resulting ray should be
  73648. * @returns a ray in the direction the controller is pointing
  73649. */
  73650. PoseEnabledController.prototype.getForwardRay = function (length) {
  73651. if (length === void 0) { length = 100; }
  73652. if (!this.mesh) {
  73653. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  73654. }
  73655. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  73656. var origin = m.getTranslation();
  73657. var forward = new BABYLON.Vector3(0, 0, -1);
  73658. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73659. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73660. return new BABYLON.Ray(origin, direction, length);
  73661. };
  73662. /**
  73663. * Name of the child mesh that can be used to cast a ray from the controller
  73664. */
  73665. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  73666. return PoseEnabledController;
  73667. }(BABYLON.Gamepad));
  73668. BABYLON.PoseEnabledController = PoseEnabledController;
  73669. })(BABYLON || (BABYLON = {}));
  73670. //# sourceMappingURL=babylon.poseEnabledController.js.map
  73671. var BABYLON;
  73672. (function (BABYLON) {
  73673. /**
  73674. * Defines the WebVRController object that represents controllers tracked in 3D space
  73675. */
  73676. var WebVRController = /** @class */ (function (_super) {
  73677. __extends(WebVRController, _super);
  73678. /**
  73679. * Creates a new WebVRController from a gamepad
  73680. * @param vrGamepad the gamepad that the WebVRController should be created from
  73681. */
  73682. function WebVRController(vrGamepad) {
  73683. var _this = _super.call(this, vrGamepad) || this;
  73684. // Observables
  73685. /**
  73686. * Fired when the trigger state has changed
  73687. */
  73688. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  73689. /**
  73690. * Fired when the main button state has changed
  73691. */
  73692. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  73693. /**
  73694. * Fired when the secondary button state has changed
  73695. */
  73696. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  73697. /**
  73698. * Fired when the pad state has changed
  73699. */
  73700. _this.onPadStateChangedObservable = new BABYLON.Observable();
  73701. /**
  73702. * Fired when controllers stick values have changed
  73703. */
  73704. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  73705. /**
  73706. * X and Y axis corrisponding to the controllers joystick
  73707. */
  73708. _this.pad = { x: 0, y: 0 };
  73709. // avoid GC, store state in a tmp object
  73710. _this._changes = {
  73711. pressChanged: false,
  73712. touchChanged: false,
  73713. valueChanged: false,
  73714. changed: false
  73715. };
  73716. _this._buttons = new Array(vrGamepad.buttons.length);
  73717. _this.hand = vrGamepad.hand;
  73718. return _this;
  73719. }
  73720. /**
  73721. * Fired when a controller button's state has changed
  73722. * @param callback the callback containing the button that was modified
  73723. */
  73724. WebVRController.prototype.onButtonStateChange = function (callback) {
  73725. this._onButtonStateChange = callback;
  73726. };
  73727. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  73728. /**
  73729. * The default controller model for the controller
  73730. */
  73731. get: function () {
  73732. return this._defaultModel;
  73733. },
  73734. enumerable: true,
  73735. configurable: true
  73736. });
  73737. /**
  73738. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  73739. */
  73740. WebVRController.prototype.update = function () {
  73741. _super.prototype.update.call(this);
  73742. for (var index = 0; index < this._buttons.length; index++) {
  73743. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  73744. }
  73745. ;
  73746. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  73747. this.pad.x = this.leftStick.x;
  73748. this.pad.y = this.leftStick.y;
  73749. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  73750. }
  73751. };
  73752. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  73753. if (!newState) {
  73754. newState = {
  73755. pressed: false,
  73756. touched: false,
  73757. value: 0
  73758. };
  73759. }
  73760. if (!currentState) {
  73761. this._buttons[buttonIndex] = {
  73762. pressed: newState.pressed,
  73763. touched: newState.touched,
  73764. value: newState.value
  73765. };
  73766. return;
  73767. }
  73768. this._checkChanges(newState, currentState);
  73769. if (this._changes.changed) {
  73770. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  73771. this._handleButtonChange(buttonIndex, newState, this._changes);
  73772. }
  73773. this._buttons[buttonIndex].pressed = newState.pressed;
  73774. this._buttons[buttonIndex].touched = newState.touched;
  73775. // oculus triggers are never 0, thou not touched.
  73776. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  73777. };
  73778. WebVRController.prototype._checkChanges = function (newState, currentState) {
  73779. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  73780. this._changes.touchChanged = newState.touched !== currentState.touched;
  73781. this._changes.valueChanged = newState.value !== currentState.value;
  73782. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  73783. return this._changes;
  73784. };
  73785. /**
  73786. * Disposes of th webVRCOntroller
  73787. */
  73788. WebVRController.prototype.dispose = function () {
  73789. _super.prototype.dispose.call(this);
  73790. this.onTriggerStateChangedObservable.clear();
  73791. this.onMainButtonStateChangedObservable.clear();
  73792. this.onSecondaryButtonStateChangedObservable.clear();
  73793. this.onPadStateChangedObservable.clear();
  73794. this.onPadValuesChangedObservable.clear();
  73795. };
  73796. return WebVRController;
  73797. }(BABYLON.PoseEnabledController));
  73798. BABYLON.WebVRController = WebVRController;
  73799. })(BABYLON || (BABYLON = {}));
  73800. //# sourceMappingURL=babylon.webVRController.js.map
  73801. var BABYLON;
  73802. (function (BABYLON) {
  73803. /**
  73804. * Oculus Touch Controller
  73805. */
  73806. var OculusTouchController = /** @class */ (function (_super) {
  73807. __extends(OculusTouchController, _super);
  73808. /**
  73809. * Creates a new OculusTouchController from a gamepad
  73810. * @param vrGamepad the gamepad that the controller should be created from
  73811. */
  73812. function OculusTouchController(vrGamepad) {
  73813. var _this = _super.call(this, vrGamepad) || this;
  73814. /**
  73815. * Fired when the secondary trigger on this controller is modified
  73816. */
  73817. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  73818. /**
  73819. * Fired when the thumb rest on this controller is modified
  73820. */
  73821. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  73822. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  73823. return _this;
  73824. }
  73825. /**
  73826. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73827. * @param scene scene in which to add meshes
  73828. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73829. */
  73830. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73831. var _this = this;
  73832. var meshName;
  73833. // Hand
  73834. if (this.hand === 'left') {
  73835. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  73836. }
  73837. else { // Right is the default if no hand is specified
  73838. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  73839. }
  73840. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  73841. /*
  73842. Parent Mesh name: oculus_touch_left
  73843. - body
  73844. - trigger
  73845. - thumbstick
  73846. - grip
  73847. - button_y
  73848. - button_x
  73849. - button_enter
  73850. */
  73851. _this._defaultModel = newMeshes[1];
  73852. _this.attachToMesh(_this._defaultModel);
  73853. if (meshLoaded) {
  73854. meshLoaded(_this._defaultModel);
  73855. }
  73856. });
  73857. };
  73858. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  73859. /**
  73860. * Fired when the A button on this controller is modified
  73861. */
  73862. get: function () {
  73863. if (this.hand === 'right') {
  73864. return this.onMainButtonStateChangedObservable;
  73865. }
  73866. else {
  73867. throw new Error('No A button on left hand');
  73868. }
  73869. },
  73870. enumerable: true,
  73871. configurable: true
  73872. });
  73873. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  73874. /**
  73875. * Fired when the B button on this controller is modified
  73876. */
  73877. get: function () {
  73878. if (this.hand === 'right') {
  73879. return this.onSecondaryButtonStateChangedObservable;
  73880. }
  73881. else {
  73882. throw new Error('No B button on left hand');
  73883. }
  73884. },
  73885. enumerable: true,
  73886. configurable: true
  73887. });
  73888. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  73889. /**
  73890. * Fired when the X button on this controller is modified
  73891. */
  73892. get: function () {
  73893. if (this.hand === 'left') {
  73894. return this.onMainButtonStateChangedObservable;
  73895. }
  73896. else {
  73897. throw new Error('No X button on right hand');
  73898. }
  73899. },
  73900. enumerable: true,
  73901. configurable: true
  73902. });
  73903. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  73904. /**
  73905. * Fired when the Y button on this controller is modified
  73906. */
  73907. get: function () {
  73908. if (this.hand === 'left') {
  73909. return this.onSecondaryButtonStateChangedObservable;
  73910. }
  73911. else {
  73912. throw new Error('No Y button on right hand');
  73913. }
  73914. },
  73915. enumerable: true,
  73916. configurable: true
  73917. });
  73918. /**
  73919. * Called once for each button that changed state since the last frame
  73920. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  73921. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  73922. * 2) secondary trigger (same)
  73923. * 3) A (right) X (left), touch, pressed = value
  73924. * 4) B / Y
  73925. * 5) thumb rest
  73926. * @param buttonIdx Which button index changed
  73927. * @param state New state of the button
  73928. * @param changes Which properties on the state changed since last frame
  73929. */
  73930. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73931. var notifyObject = state; //{ state: state, changes: changes };
  73932. var triggerDirection = this.hand === 'right' ? -1 : 1;
  73933. switch (buttonIdx) {
  73934. case 0:
  73935. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73936. return;
  73937. case 1: // index trigger
  73938. if (this._defaultModel) {
  73939. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  73940. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  73941. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  73942. }
  73943. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73944. return;
  73945. case 2: // secondary trigger
  73946. if (this._defaultModel) {
  73947. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  73948. }
  73949. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  73950. return;
  73951. case 3:
  73952. if (this._defaultModel) {
  73953. if (notifyObject.pressed) {
  73954. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  73955. }
  73956. else {
  73957. (this._defaultModel.getChildren()[1]).position.y = 0;
  73958. }
  73959. }
  73960. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73961. return;
  73962. case 4:
  73963. if (this._defaultModel) {
  73964. if (notifyObject.pressed) {
  73965. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73966. }
  73967. else {
  73968. (this._defaultModel.getChildren()[2]).position.y = 0;
  73969. }
  73970. }
  73971. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73972. return;
  73973. case 5:
  73974. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  73975. return;
  73976. }
  73977. };
  73978. /**
  73979. * Base Url for the controller model.
  73980. */
  73981. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  73982. /**
  73983. * File name for the left controller model.
  73984. */
  73985. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  73986. /**
  73987. * File name for the right controller model.
  73988. */
  73989. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  73990. return OculusTouchController;
  73991. }(BABYLON.WebVRController));
  73992. BABYLON.OculusTouchController = OculusTouchController;
  73993. })(BABYLON || (BABYLON = {}));
  73994. //# sourceMappingURL=babylon.oculusTouchController.js.map
  73995. var BABYLON;
  73996. (function (BABYLON) {
  73997. /**
  73998. * Vive Controller
  73999. */
  74000. var ViveController = /** @class */ (function (_super) {
  74001. __extends(ViveController, _super);
  74002. /**
  74003. * Creates a new ViveController from a gamepad
  74004. * @param vrGamepad the gamepad that the controller should be created from
  74005. */
  74006. function ViveController(vrGamepad) {
  74007. var _this = _super.call(this, vrGamepad) || this;
  74008. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  74009. _this._invertLeftStickY = true;
  74010. return _this;
  74011. }
  74012. /**
  74013. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74014. * @param scene scene in which to add meshes
  74015. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74016. */
  74017. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74018. var _this = this;
  74019. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  74020. /*
  74021. Parent Mesh name: ViveWand
  74022. - body
  74023. - r_gripper
  74024. - l_gripper
  74025. - menu_button
  74026. - system_button
  74027. - trackpad
  74028. - trigger
  74029. - LED
  74030. */
  74031. _this._defaultModel = newMeshes[1];
  74032. _this.attachToMesh(_this._defaultModel);
  74033. if (meshLoaded) {
  74034. meshLoaded(_this._defaultModel);
  74035. }
  74036. });
  74037. };
  74038. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  74039. /**
  74040. * Fired when the left button on this controller is modified
  74041. */
  74042. get: function () {
  74043. return this.onMainButtonStateChangedObservable;
  74044. },
  74045. enumerable: true,
  74046. configurable: true
  74047. });
  74048. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  74049. /**
  74050. * Fired when the right button on this controller is modified
  74051. */
  74052. get: function () {
  74053. return this.onMainButtonStateChangedObservable;
  74054. },
  74055. enumerable: true,
  74056. configurable: true
  74057. });
  74058. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  74059. /**
  74060. * Fired when the menu button on this controller is modified
  74061. */
  74062. get: function () {
  74063. return this.onSecondaryButtonStateChangedObservable;
  74064. },
  74065. enumerable: true,
  74066. configurable: true
  74067. });
  74068. /**
  74069. * Called once for each button that changed state since the last frame
  74070. * Vive mapping:
  74071. * 0: touchpad
  74072. * 1: trigger
  74073. * 2: left AND right buttons
  74074. * 3: menu button
  74075. * @param buttonIdx Which button index changed
  74076. * @param state New state of the button
  74077. * @param changes Which properties on the state changed since last frame
  74078. */
  74079. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74080. var notifyObject = state; //{ state: state, changes: changes };
  74081. switch (buttonIdx) {
  74082. case 0:
  74083. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74084. return;
  74085. case 1: // index trigger
  74086. if (this._defaultModel) {
  74087. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  74088. }
  74089. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74090. return;
  74091. case 2: // left AND right button
  74092. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74093. return;
  74094. case 3:
  74095. if (this._defaultModel) {
  74096. if (notifyObject.pressed) {
  74097. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74098. }
  74099. else {
  74100. (this._defaultModel.getChildren()[2]).position.y = 0;
  74101. }
  74102. }
  74103. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74104. return;
  74105. }
  74106. };
  74107. /**
  74108. * Base Url for the controller model.
  74109. */
  74110. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  74111. /**
  74112. * File name for the controller model.
  74113. */
  74114. ViveController.MODEL_FILENAME = 'wand.babylon';
  74115. return ViveController;
  74116. }(BABYLON.WebVRController));
  74117. BABYLON.ViveController = ViveController;
  74118. })(BABYLON || (BABYLON = {}));
  74119. //# sourceMappingURL=babylon.viveController.js.map
  74120. var BABYLON;
  74121. (function (BABYLON) {
  74122. /**
  74123. * Generic Controller
  74124. */
  74125. var GenericController = /** @class */ (function (_super) {
  74126. __extends(GenericController, _super);
  74127. /**
  74128. * Creates a new GenericController from a gamepad
  74129. * @param vrGamepad the gamepad that the controller should be created from
  74130. */
  74131. function GenericController(vrGamepad) {
  74132. return _super.call(this, vrGamepad) || this;
  74133. }
  74134. /**
  74135. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74136. * @param scene scene in which to add meshes
  74137. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74138. */
  74139. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74140. var _this = this;
  74141. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  74142. _this._defaultModel = newMeshes[1];
  74143. _this.attachToMesh(_this._defaultModel);
  74144. if (meshLoaded) {
  74145. meshLoaded(_this._defaultModel);
  74146. }
  74147. });
  74148. };
  74149. /**
  74150. * Called once for each button that changed state since the last frame
  74151. * @param buttonIdx Which button index changed
  74152. * @param state New state of the button
  74153. * @param changes Which properties on the state changed since last frame
  74154. */
  74155. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74156. console.log("Button id: " + buttonIdx + "state: ");
  74157. console.dir(state);
  74158. };
  74159. /**
  74160. * Base Url for the controller model.
  74161. */
  74162. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74163. /**
  74164. * File name for the controller model.
  74165. */
  74166. GenericController.MODEL_FILENAME = 'generic.babylon';
  74167. return GenericController;
  74168. }(BABYLON.WebVRController));
  74169. BABYLON.GenericController = GenericController;
  74170. })(BABYLON || (BABYLON = {}));
  74171. //# sourceMappingURL=babylon.genericController.js.map
  74172. var BABYLON;
  74173. (function (BABYLON) {
  74174. /**
  74175. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  74176. */
  74177. var LoadedMeshInfo = /** @class */ (function () {
  74178. function LoadedMeshInfo() {
  74179. /**
  74180. * Map of the button meshes contained in the controller
  74181. */
  74182. this.buttonMeshes = {};
  74183. /**
  74184. * Map of the axis meshes contained in the controller
  74185. */
  74186. this.axisMeshes = {};
  74187. }
  74188. return LoadedMeshInfo;
  74189. }());
  74190. /**
  74191. * Defines the WindowsMotionController object that the state of the windows motion controller
  74192. */
  74193. var WindowsMotionController = /** @class */ (function (_super) {
  74194. __extends(WindowsMotionController, _super);
  74195. /**
  74196. * Creates a new WindowsMotionController from a gamepad
  74197. * @param vrGamepad the gamepad that the controller should be created from
  74198. */
  74199. function WindowsMotionController(vrGamepad) {
  74200. var _this = _super.call(this, vrGamepad) || this;
  74201. _this._mapping = {
  74202. // Semantic button names
  74203. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  74204. // A mapping of the button name to glTF model node name
  74205. // that should be transformed by button value.
  74206. buttonMeshNames: {
  74207. 'trigger': 'SELECT',
  74208. 'menu': 'MENU',
  74209. 'grip': 'GRASP',
  74210. 'thumbstick': 'THUMBSTICK_PRESS',
  74211. 'trackpad': 'TOUCHPAD_PRESS'
  74212. },
  74213. // This mapping is used to translate from the Motion Controller to Babylon semantics
  74214. buttonObservableNames: {
  74215. 'trigger': 'onTriggerStateChangedObservable',
  74216. 'menu': 'onSecondaryButtonStateChangedObservable',
  74217. 'grip': 'onMainButtonStateChangedObservable',
  74218. 'thumbstick': 'onPadStateChangedObservable',
  74219. 'trackpad': 'onTrackpadChangedObservable'
  74220. },
  74221. // A mapping of the axis name to glTF model node name
  74222. // that should be transformed by axis value.
  74223. // This array mirrors the browserGamepad.axes array, such that
  74224. // the mesh corresponding to axis 0 is in this array index 0.
  74225. axisMeshNames: [
  74226. 'THUMBSTICK_X',
  74227. 'THUMBSTICK_Y',
  74228. 'TOUCHPAD_TOUCH_X',
  74229. 'TOUCHPAD_TOUCH_Y'
  74230. ],
  74231. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  74232. };
  74233. /**
  74234. * Fired when the trackpad on this controller is clicked
  74235. */
  74236. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  74237. /**
  74238. * Fired when the trackpad on this controller is modified
  74239. */
  74240. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  74241. /**
  74242. * The current x and y values of this controller's trackpad
  74243. */
  74244. _this.trackpad = { x: 0, y: 0 };
  74245. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  74246. _this._loadedMeshInfo = null;
  74247. return _this;
  74248. }
  74249. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  74250. /**
  74251. * Fired when the trigger on this controller is modified
  74252. */
  74253. get: function () {
  74254. return this.onTriggerStateChangedObservable;
  74255. },
  74256. enumerable: true,
  74257. configurable: true
  74258. });
  74259. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  74260. /**
  74261. * Fired when the menu button on this controller is modified
  74262. */
  74263. get: function () {
  74264. return this.onSecondaryButtonStateChangedObservable;
  74265. },
  74266. enumerable: true,
  74267. configurable: true
  74268. });
  74269. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  74270. /**
  74271. * Fired when the grip button on this controller is modified
  74272. */
  74273. get: function () {
  74274. return this.onMainButtonStateChangedObservable;
  74275. },
  74276. enumerable: true,
  74277. configurable: true
  74278. });
  74279. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  74280. /**
  74281. * Fired when the thumbstick button on this controller is modified
  74282. */
  74283. get: function () {
  74284. return this.onPadStateChangedObservable;
  74285. },
  74286. enumerable: true,
  74287. configurable: true
  74288. });
  74289. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  74290. /**
  74291. * Fired when the touchpad button on this controller is modified
  74292. */
  74293. get: function () {
  74294. return this.onTrackpadChangedObservable;
  74295. },
  74296. enumerable: true,
  74297. configurable: true
  74298. });
  74299. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  74300. /**
  74301. * Fired when the touchpad values on this controller are modified
  74302. */
  74303. get: function () {
  74304. return this.onTrackpadValuesChangedObservable;
  74305. },
  74306. enumerable: true,
  74307. configurable: true
  74308. });
  74309. WindowsMotionController.prototype._updateTrackpad = function () {
  74310. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  74311. this.trackpad.x = this.browserGamepad["axes"][2];
  74312. this.trackpad.y = this.browserGamepad["axes"][3];
  74313. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  74314. }
  74315. };
  74316. /**
  74317. * Called once per frame by the engine.
  74318. */
  74319. WindowsMotionController.prototype.update = function () {
  74320. _super.prototype.update.call(this);
  74321. if (this.browserGamepad.axes) {
  74322. this._updateTrackpad();
  74323. // Only need to animate axes if there is a loaded mesh
  74324. if (this._loadedMeshInfo) {
  74325. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  74326. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  74327. }
  74328. }
  74329. }
  74330. };
  74331. /**
  74332. * Called once for each button that changed state since the last frame
  74333. * @param buttonIdx Which button index changed
  74334. * @param state New state of the button
  74335. * @param changes Which properties on the state changed since last frame
  74336. */
  74337. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74338. var buttonName = this._mapping.buttons[buttonIdx];
  74339. if (!buttonName) {
  74340. return;
  74341. }
  74342. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  74343. this._updateTrackpad();
  74344. // Only emit events for buttons that we know how to map from index to name
  74345. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  74346. if (observable) {
  74347. observable.notifyObservers(state);
  74348. }
  74349. this._lerpButtonTransform(buttonName, state.value);
  74350. };
  74351. /**
  74352. * Moves the buttons on the controller mesh based on their current state
  74353. * @param buttonName the name of the button to move
  74354. * @param buttonValue the value of the button which determines the buttons new position
  74355. */
  74356. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  74357. // If there is no loaded mesh, there is nothing to transform.
  74358. if (!this._loadedMeshInfo) {
  74359. return;
  74360. }
  74361. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  74362. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  74363. return;
  74364. }
  74365. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  74366. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  74367. };
  74368. /**
  74369. * Moves the axis on the controller mesh based on its current state
  74370. * @param axis the index of the axis
  74371. * @param axisValue the value of the axis which determines the meshes new position
  74372. * @hidden
  74373. */
  74374. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  74375. if (!this._loadedMeshInfo) {
  74376. return;
  74377. }
  74378. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  74379. if (!meshInfo) {
  74380. return;
  74381. }
  74382. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  74383. return;
  74384. }
  74385. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  74386. var lerpValue = axisValue * 0.5 + 0.5;
  74387. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  74388. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  74389. };
  74390. /**
  74391. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74392. * @param scene scene in which to add meshes
  74393. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74394. */
  74395. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  74396. var _this = this;
  74397. if (forceDefault === void 0) { forceDefault = false; }
  74398. var path;
  74399. var filename;
  74400. // Checking if GLB loader is present
  74401. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  74402. // Determine the device specific folder based on the ID suffix
  74403. var device = 'default';
  74404. if (this.id && !forceDefault) {
  74405. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  74406. device = ((match && match[0]) || device);
  74407. }
  74408. // Hand
  74409. if (this.hand === 'left') {
  74410. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  74411. }
  74412. else { // Right is the default if no hand is specified
  74413. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  74414. }
  74415. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  74416. }
  74417. else {
  74418. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  74419. path = BABYLON.GenericController.MODEL_BASE_URL;
  74420. filename = BABYLON.GenericController.MODEL_FILENAME;
  74421. }
  74422. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  74423. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  74424. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  74425. if (!_this._loadedMeshInfo) {
  74426. return;
  74427. }
  74428. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  74429. _this.attachToMesh(_this._defaultModel);
  74430. if (meshLoaded) {
  74431. meshLoaded(_this._defaultModel);
  74432. }
  74433. }, null, function (scene, message) {
  74434. BABYLON.Tools.Log(message);
  74435. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  74436. if (!forceDefault) {
  74437. _this.initControllerMesh(scene, meshLoaded, true);
  74438. }
  74439. });
  74440. };
  74441. /**
  74442. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  74443. * can be transformed by button presses and axes values, based on this._mapping.
  74444. *
  74445. * @param scene scene in which the meshes exist
  74446. * @param meshes list of meshes that make up the controller model to process
  74447. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  74448. */
  74449. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  74450. var loadedMeshInfo = null;
  74451. // Create a new mesh to contain the glTF hierarchy
  74452. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  74453. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  74454. var childMesh = null;
  74455. for (var i = 0; i < meshes.length; i++) {
  74456. var mesh = meshes[i];
  74457. if (!mesh.parent) {
  74458. // Exclude controller meshes from picking results
  74459. mesh.isPickable = false;
  74460. // Handle root node, attach to the new parentMesh
  74461. childMesh = mesh;
  74462. break;
  74463. }
  74464. }
  74465. if (childMesh) {
  74466. childMesh.setParent(parentMesh);
  74467. // Create our mesh info. Note that this method will always return non-null.
  74468. loadedMeshInfo = this.createMeshInfo(parentMesh);
  74469. }
  74470. else {
  74471. BABYLON.Tools.Warn('Could not find root node in model file.');
  74472. }
  74473. return loadedMeshInfo;
  74474. };
  74475. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  74476. var loadedMeshInfo = new LoadedMeshInfo();
  74477. var i;
  74478. loadedMeshInfo.rootNode = rootNode;
  74479. // Reset the caches
  74480. loadedMeshInfo.buttonMeshes = {};
  74481. loadedMeshInfo.axisMeshes = {};
  74482. // Button Meshes
  74483. for (i = 0; i < this._mapping.buttons.length; i++) {
  74484. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  74485. if (!buttonMeshName) {
  74486. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  74487. continue;
  74488. }
  74489. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  74490. if (!buttonMesh) {
  74491. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  74492. continue;
  74493. }
  74494. var buttonMeshInfo = {
  74495. index: i,
  74496. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  74497. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  74498. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  74499. };
  74500. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  74501. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  74502. }
  74503. else {
  74504. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  74505. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  74506. '(VALUE: ' + !!buttonMeshInfo.value +
  74507. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  74508. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  74509. ')');
  74510. }
  74511. }
  74512. // Axis Meshes
  74513. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  74514. var axisMeshName = this._mapping.axisMeshNames[i];
  74515. if (!axisMeshName) {
  74516. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  74517. continue;
  74518. }
  74519. var axisMesh = getChildByName(rootNode, axisMeshName);
  74520. if (!axisMesh) {
  74521. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  74522. continue;
  74523. }
  74524. var axisMeshInfo = {
  74525. index: i,
  74526. value: getImmediateChildByName(axisMesh, 'VALUE'),
  74527. min: getImmediateChildByName(axisMesh, 'MIN'),
  74528. max: getImmediateChildByName(axisMesh, 'MAX')
  74529. };
  74530. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  74531. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  74532. }
  74533. else {
  74534. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  74535. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  74536. '(VALUE: ' + !!axisMeshInfo.value +
  74537. ', MIN: ' + !!axisMeshInfo.min +
  74538. ', MAX:' + !!axisMeshInfo.max +
  74539. ')');
  74540. }
  74541. }
  74542. // Pointing Ray
  74543. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  74544. if (!loadedMeshInfo.pointingPoseNode) {
  74545. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  74546. }
  74547. else {
  74548. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  74549. }
  74550. return loadedMeshInfo;
  74551. // Look through all children recursively. This will return null if no mesh exists with the given name.
  74552. function getChildByName(node, name) {
  74553. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  74554. }
  74555. // Look through only immediate children. This will return null if no mesh exists with the given name.
  74556. function getImmediateChildByName(node, name) {
  74557. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  74558. }
  74559. };
  74560. /**
  74561. * Gets the ray of the controller in the direction the controller is pointing
  74562. * @param length the length the resulting ray should be
  74563. * @returns a ray in the direction the controller is pointing
  74564. */
  74565. WindowsMotionController.prototype.getForwardRay = function (length) {
  74566. if (length === void 0) { length = 100; }
  74567. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  74568. return _super.prototype.getForwardRay.call(this, length);
  74569. }
  74570. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  74571. var origin = m.getTranslation();
  74572. var forward = new BABYLON.Vector3(0, 0, -1);
  74573. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74574. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74575. return new BABYLON.Ray(origin, direction, length);
  74576. };
  74577. /**
  74578. * Disposes of the controller
  74579. */
  74580. WindowsMotionController.prototype.dispose = function () {
  74581. _super.prototype.dispose.call(this);
  74582. this.onTrackpadChangedObservable.clear();
  74583. };
  74584. /**
  74585. * The base url used to load the left and right controller models
  74586. */
  74587. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  74588. /**
  74589. * The name of the left controller model file
  74590. */
  74591. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  74592. /**
  74593. * The name of the right controller model file
  74594. */
  74595. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  74596. /**
  74597. * The controller name prefix for this controller type
  74598. */
  74599. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  74600. /**
  74601. * The controller id pattern for this controller type
  74602. */
  74603. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  74604. return WindowsMotionController;
  74605. }(BABYLON.WebVRController));
  74606. BABYLON.WindowsMotionController = WindowsMotionController;
  74607. })(BABYLON || (BABYLON = {}));
  74608. //# sourceMappingURL=babylon.windowsMotionController.js.map
  74609. var BABYLON;
  74610. (function (BABYLON) {
  74611. /**
  74612. * Gear VR Controller
  74613. */
  74614. var GearVRController = /** @class */ (function (_super) {
  74615. __extends(GearVRController, _super);
  74616. /**
  74617. * Creates a new GearVRController from a gamepad
  74618. * @param vrGamepad the gamepad that the controller should be created from
  74619. */
  74620. function GearVRController(vrGamepad) {
  74621. var _this = _super.call(this, vrGamepad) || this;
  74622. _this._maxRotationDistFromHeadset = Math.PI / 5;
  74623. _this._draggedRoomRotation = 0;
  74624. _this._tmpVector = new BABYLON.Vector3();
  74625. _this._buttonIndexToObservableNameMap = [
  74626. 'onTrackpadChangedObservable',
  74627. 'onTriggerStateChangedObservable' // Trigger
  74628. ];
  74629. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  74630. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  74631. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  74632. return _this;
  74633. }
  74634. /**
  74635. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74636. * @param poseData raw pose fromthe device
  74637. */
  74638. GearVRController.prototype.updateFromDevice = function (poseData) {
  74639. _super.prototype.updateFromDevice.call(this, poseData);
  74640. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  74641. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  74642. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  74643. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  74644. // Find the radian distance away that the headset is from the controllers rotation
  74645. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  74646. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  74647. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  74648. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  74649. this._draggedRoomRotation += rotationAmount;
  74650. // Rotate controller around headset
  74651. var sin = Math.sin(-rotationAmount);
  74652. var cos = Math.cos(-rotationAmount);
  74653. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  74654. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  74655. }
  74656. }
  74657. }
  74658. };
  74659. /**
  74660. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74661. * @param scene scene in which to add meshes
  74662. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74663. */
  74664. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74665. var _this = this;
  74666. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  74667. // Offset the controller so it will rotate around the users wrist
  74668. var mesh = new BABYLON.Mesh("", scene);
  74669. newMeshes[1].parent = mesh;
  74670. newMeshes[1].position.z = -0.15;
  74671. _this._defaultModel = mesh;
  74672. _this.attachToMesh(_this._defaultModel);
  74673. if (meshLoaded) {
  74674. meshLoaded(_this._defaultModel);
  74675. }
  74676. });
  74677. };
  74678. /**
  74679. * Called once for each button that changed state since the last frame
  74680. * @param buttonIdx Which button index changed
  74681. * @param state New state of the button
  74682. * @param changes Which properties on the state changed since last frame
  74683. */
  74684. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74685. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  74686. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  74687. // Only emit events for buttons that we know how to map from index to observable
  74688. var observable = this[observableName];
  74689. if (observable) {
  74690. observable.notifyObservers(state);
  74691. }
  74692. }
  74693. };
  74694. /**
  74695. * Base Url for the controller model.
  74696. */
  74697. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74698. /**
  74699. * File name for the controller model.
  74700. */
  74701. GearVRController.MODEL_FILENAME = 'generic.babylon';
  74702. /**
  74703. * Gamepad Id prefix used to identify this controller.
  74704. */
  74705. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  74706. return GearVRController;
  74707. }(BABYLON.WebVRController));
  74708. BABYLON.GearVRController = GearVRController;
  74709. })(BABYLON || (BABYLON = {}));
  74710. //# sourceMappingURL=babylon.gearVRController.js.map
  74711. var BABYLON;
  74712. (function (BABYLON) {
  74713. /**
  74714. * Google Daydream controller
  74715. */
  74716. var DaydreamController = /** @class */ (function (_super) {
  74717. __extends(DaydreamController, _super);
  74718. /**
  74719. * Creates a new DaydreamController from a gamepad
  74720. * @param vrGamepad the gamepad that the controller should be created from
  74721. */
  74722. function DaydreamController(vrGamepad) {
  74723. var _this = _super.call(this, vrGamepad) || this;
  74724. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  74725. return _this;
  74726. }
  74727. /**
  74728. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74729. * @param scene scene in which to add meshes
  74730. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74731. */
  74732. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74733. var _this = this;
  74734. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  74735. _this._defaultModel = newMeshes[1];
  74736. _this.attachToMesh(_this._defaultModel);
  74737. if (meshLoaded) {
  74738. meshLoaded(_this._defaultModel);
  74739. }
  74740. });
  74741. };
  74742. /**
  74743. * Called once for each button that changed state since the last frame
  74744. * @param buttonIdx Which button index changed
  74745. * @param state New state of the button
  74746. * @param changes Which properties on the state changed since last frame
  74747. */
  74748. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74749. // Daydream controller only has 1 GamepadButton (on the trackpad).
  74750. if (buttonIdx === 0) {
  74751. var observable = this.onTriggerStateChangedObservable;
  74752. if (observable) {
  74753. observable.notifyObservers(state);
  74754. }
  74755. }
  74756. else {
  74757. // If the app or home buttons are ever made available
  74758. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  74759. }
  74760. };
  74761. /**
  74762. * Base Url for the controller model.
  74763. */
  74764. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74765. /**
  74766. * File name for the controller model.
  74767. */
  74768. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  74769. /**
  74770. * Gamepad Id prefix used to identify Daydream Controller.
  74771. */
  74772. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  74773. return DaydreamController;
  74774. }(BABYLON.WebVRController));
  74775. BABYLON.DaydreamController = DaydreamController;
  74776. })(BABYLON || (BABYLON = {}));
  74777. //# sourceMappingURL=babylon.daydreamController.js.map
  74778. var BABYLON;
  74779. (function (BABYLON) {
  74780. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  74781. get: function () {
  74782. if (!this._gamepadManager) {
  74783. this._gamepadManager = new BABYLON.GamepadManager(this);
  74784. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  74785. if (!component) {
  74786. component = new GamepadSystemSceneComponent(this);
  74787. this._addComponent(component);
  74788. }
  74789. }
  74790. return this._gamepadManager;
  74791. },
  74792. enumerable: true,
  74793. configurable: true
  74794. });
  74795. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  74796. this.add(new BABYLON.FreeCameraGamepadInput());
  74797. return this;
  74798. };
  74799. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  74800. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  74801. return this;
  74802. };
  74803. /**
  74804. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  74805. */
  74806. var GamepadSystemSceneComponent = /** @class */ (function () {
  74807. /**
  74808. * Creates a new instance of the component for the given scene
  74809. * @param scene Defines the scene to register the component in
  74810. */
  74811. function GamepadSystemSceneComponent(scene) {
  74812. /**
  74813. * The component name helpfull to identify the component in the list of scene components.
  74814. */
  74815. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  74816. this.scene = scene;
  74817. }
  74818. /**
  74819. * Registers the component in a given scene
  74820. */
  74821. GamepadSystemSceneComponent.prototype.register = function () {
  74822. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  74823. };
  74824. /**
  74825. * Rebuilds the elements related to this component in case of
  74826. * context lost for instance.
  74827. */
  74828. GamepadSystemSceneComponent.prototype.rebuild = function () {
  74829. // Nothing to do for gamepads
  74830. };
  74831. /**
  74832. * Disposes the component and the associated ressources
  74833. */
  74834. GamepadSystemSceneComponent.prototype.dispose = function () {
  74835. var gamepadManager = this.scene._gamepadManager;
  74836. if (gamepadManager) {
  74837. gamepadManager.dispose();
  74838. this.scene._gamepadManager = null;
  74839. }
  74840. };
  74841. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  74842. var gamepadManager = this.scene._gamepadManager;
  74843. if (gamepadManager && gamepadManager._isMonitoring) {
  74844. gamepadManager._checkGamepadsStatus();
  74845. }
  74846. };
  74847. return GamepadSystemSceneComponent;
  74848. }());
  74849. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  74850. })(BABYLON || (BABYLON = {}));
  74851. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  74852. var BABYLON;
  74853. (function (BABYLON) {
  74854. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  74855. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  74856. });
  74857. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  74858. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  74859. });
  74860. var FollowCamera = /** @class */ (function (_super) {
  74861. __extends(FollowCamera, _super);
  74862. function FollowCamera(name, position, scene, lockedTarget) {
  74863. if (lockedTarget === void 0) { lockedTarget = null; }
  74864. var _this = _super.call(this, name, position, scene) || this;
  74865. _this.radius = 12;
  74866. _this.rotationOffset = 0;
  74867. _this.heightOffset = 4;
  74868. _this.cameraAcceleration = 0.05;
  74869. _this.maxCameraSpeed = 20;
  74870. _this.lockedTarget = lockedTarget;
  74871. return _this;
  74872. }
  74873. FollowCamera.prototype.getRadians = function (degrees) {
  74874. return degrees * Math.PI / 180;
  74875. };
  74876. FollowCamera.prototype.follow = function (cameraTarget) {
  74877. if (!cameraTarget)
  74878. return;
  74879. var yRotation;
  74880. if (cameraTarget.rotationQuaternion) {
  74881. var rotMatrix = new BABYLON.Matrix();
  74882. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  74883. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  74884. }
  74885. else {
  74886. yRotation = cameraTarget.rotation.y;
  74887. }
  74888. var radians = this.getRadians(this.rotationOffset) + yRotation;
  74889. var targetPosition = cameraTarget.getAbsolutePosition();
  74890. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  74891. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  74892. var dx = targetX - this.position.x;
  74893. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  74894. var dz = (targetZ) - this.position.z;
  74895. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  74896. var vy = dy * this.cameraAcceleration;
  74897. var vz = dz * this.cameraAcceleration * 2;
  74898. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  74899. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74900. }
  74901. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  74902. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74903. }
  74904. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  74905. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74906. }
  74907. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  74908. this.setTarget(targetPosition);
  74909. };
  74910. FollowCamera.prototype._checkInputs = function () {
  74911. _super.prototype._checkInputs.call(this);
  74912. if (this.lockedTarget) {
  74913. this.follow(this.lockedTarget);
  74914. }
  74915. };
  74916. FollowCamera.prototype.getClassName = function () {
  74917. return "FollowCamera";
  74918. };
  74919. __decorate([
  74920. BABYLON.serialize()
  74921. ], FollowCamera.prototype, "radius", void 0);
  74922. __decorate([
  74923. BABYLON.serialize()
  74924. ], FollowCamera.prototype, "rotationOffset", void 0);
  74925. __decorate([
  74926. BABYLON.serialize()
  74927. ], FollowCamera.prototype, "heightOffset", void 0);
  74928. __decorate([
  74929. BABYLON.serialize()
  74930. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  74931. __decorate([
  74932. BABYLON.serialize()
  74933. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  74934. __decorate([
  74935. BABYLON.serializeAsMeshReference("lockedTargetId")
  74936. ], FollowCamera.prototype, "lockedTarget", void 0);
  74937. return FollowCamera;
  74938. }(BABYLON.TargetCamera));
  74939. BABYLON.FollowCamera = FollowCamera;
  74940. var ArcFollowCamera = /** @class */ (function (_super) {
  74941. __extends(ArcFollowCamera, _super);
  74942. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  74943. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  74944. _this.alpha = alpha;
  74945. _this.beta = beta;
  74946. _this.radius = radius;
  74947. _this.target = target;
  74948. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  74949. _this.follow();
  74950. return _this;
  74951. }
  74952. ArcFollowCamera.prototype.follow = function () {
  74953. if (!this.target) {
  74954. return;
  74955. }
  74956. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  74957. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  74958. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  74959. var targetPosition = this.target.getAbsolutePosition();
  74960. this.position = targetPosition.add(this._cartesianCoordinates);
  74961. this.setTarget(targetPosition);
  74962. };
  74963. ArcFollowCamera.prototype._checkInputs = function () {
  74964. _super.prototype._checkInputs.call(this);
  74965. this.follow();
  74966. };
  74967. ArcFollowCamera.prototype.getClassName = function () {
  74968. return "ArcFollowCamera";
  74969. };
  74970. return ArcFollowCamera;
  74971. }(BABYLON.TargetCamera));
  74972. BABYLON.ArcFollowCamera = ArcFollowCamera;
  74973. })(BABYLON || (BABYLON = {}));
  74974. //# sourceMappingURL=babylon.followCamera.js.map
  74975. var BABYLON;
  74976. (function (BABYLON) {
  74977. // We're mainly based on the logic defined into the FreeCamera code
  74978. var UniversalCamera = /** @class */ (function (_super) {
  74979. __extends(UniversalCamera, _super);
  74980. //-- end properties for backward compatibility for inputs
  74981. function UniversalCamera(name, position, scene) {
  74982. var _this = _super.call(this, name, position, scene) || this;
  74983. _this.inputs.addGamepad();
  74984. return _this;
  74985. }
  74986. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  74987. //-- Begin properties for backward compatibility for inputs
  74988. get: function () {
  74989. var gamepad = this.inputs.attached["gamepad"];
  74990. if (gamepad)
  74991. return gamepad.gamepadAngularSensibility;
  74992. return 0;
  74993. },
  74994. set: function (value) {
  74995. var gamepad = this.inputs.attached["gamepad"];
  74996. if (gamepad)
  74997. gamepad.gamepadAngularSensibility = value;
  74998. },
  74999. enumerable: true,
  75000. configurable: true
  75001. });
  75002. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  75003. get: function () {
  75004. var gamepad = this.inputs.attached["gamepad"];
  75005. if (gamepad)
  75006. return gamepad.gamepadMoveSensibility;
  75007. return 0;
  75008. },
  75009. set: function (value) {
  75010. var gamepad = this.inputs.attached["gamepad"];
  75011. if (gamepad)
  75012. gamepad.gamepadMoveSensibility = value;
  75013. },
  75014. enumerable: true,
  75015. configurable: true
  75016. });
  75017. UniversalCamera.prototype.getClassName = function () {
  75018. return "UniversalCamera";
  75019. };
  75020. return UniversalCamera;
  75021. }(BABYLON.TouchCamera));
  75022. BABYLON.UniversalCamera = UniversalCamera;
  75023. })(BABYLON || (BABYLON = {}));
  75024. //# sourceMappingURL=babylon.universalCamera.js.map
  75025. var BABYLON;
  75026. (function (BABYLON) {
  75027. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  75028. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  75029. });
  75030. // We're mainly based on the logic defined into the FreeCamera code
  75031. var GamepadCamera = /** @class */ (function (_super) {
  75032. __extends(GamepadCamera, _super);
  75033. //-- end properties for backward compatibility for inputs
  75034. function GamepadCamera(name, position, scene) {
  75035. return _super.call(this, name, position, scene) || this;
  75036. }
  75037. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  75038. //-- Begin properties for backward compatibility for inputs
  75039. get: function () {
  75040. var gamepad = this.inputs.attached["gamepad"];
  75041. if (gamepad)
  75042. return gamepad.gamepadAngularSensibility;
  75043. return 0;
  75044. },
  75045. set: function (value) {
  75046. var gamepad = this.inputs.attached["gamepad"];
  75047. if (gamepad)
  75048. gamepad.gamepadAngularSensibility = value;
  75049. },
  75050. enumerable: true,
  75051. configurable: true
  75052. });
  75053. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  75054. get: function () {
  75055. var gamepad = this.inputs.attached["gamepad"];
  75056. if (gamepad)
  75057. return gamepad.gamepadMoveSensibility;
  75058. return 0;
  75059. },
  75060. set: function (value) {
  75061. var gamepad = this.inputs.attached["gamepad"];
  75062. if (gamepad)
  75063. gamepad.gamepadMoveSensibility = value;
  75064. },
  75065. enumerable: true,
  75066. configurable: true
  75067. });
  75068. GamepadCamera.prototype.getClassName = function () {
  75069. return "GamepadCamera";
  75070. };
  75071. return GamepadCamera;
  75072. }(BABYLON.UniversalCamera));
  75073. BABYLON.GamepadCamera = GamepadCamera;
  75074. })(BABYLON || (BABYLON = {}));
  75075. //# sourceMappingURL=babylon.gamepadCamera.js.map
  75076. var BABYLON;
  75077. (function (BABYLON) {
  75078. var PostProcessRenderPipelineManager = /** @class */ (function () {
  75079. function PostProcessRenderPipelineManager() {
  75080. this._renderPipelines = {};
  75081. }
  75082. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  75083. this._renderPipelines[renderPipeline._name] = renderPipeline;
  75084. };
  75085. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  75086. if (unique === void 0) { unique = false; }
  75087. var renderPipeline = this._renderPipelines[renderPipelineName];
  75088. if (!renderPipeline) {
  75089. return;
  75090. }
  75091. renderPipeline._attachCameras(cameras, unique);
  75092. };
  75093. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  75094. var renderPipeline = this._renderPipelines[renderPipelineName];
  75095. if (!renderPipeline) {
  75096. return;
  75097. }
  75098. renderPipeline._detachCameras(cameras);
  75099. };
  75100. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75101. var renderPipeline = this._renderPipelines[renderPipelineName];
  75102. if (!renderPipeline) {
  75103. return;
  75104. }
  75105. renderPipeline._enableEffect(renderEffectName, cameras);
  75106. };
  75107. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75108. var renderPipeline = this._renderPipelines[renderPipelineName];
  75109. if (!renderPipeline) {
  75110. return;
  75111. }
  75112. renderPipeline._disableEffect(renderEffectName, cameras);
  75113. };
  75114. PostProcessRenderPipelineManager.prototype.update = function () {
  75115. for (var renderPipelineName in this._renderPipelines) {
  75116. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75117. var pipeline = this._renderPipelines[renderPipelineName];
  75118. if (!pipeline.isSupported) {
  75119. pipeline.dispose();
  75120. delete this._renderPipelines[renderPipelineName];
  75121. }
  75122. else {
  75123. pipeline._update();
  75124. }
  75125. }
  75126. }
  75127. };
  75128. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  75129. for (var renderPipelineName in this._renderPipelines) {
  75130. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75131. var pipeline = this._renderPipelines[renderPipelineName];
  75132. pipeline._rebuild();
  75133. }
  75134. }
  75135. };
  75136. PostProcessRenderPipelineManager.prototype.dispose = function () {
  75137. for (var renderPipelineName in this._renderPipelines) {
  75138. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75139. var pipeline = this._renderPipelines[renderPipelineName];
  75140. pipeline.dispose();
  75141. }
  75142. }
  75143. };
  75144. return PostProcessRenderPipelineManager;
  75145. }());
  75146. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  75147. })(BABYLON || (BABYLON = {}));
  75148. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  75149. var BABYLON;
  75150. (function (BABYLON) {
  75151. /**
  75152. * This represents a set of one or more post processes in Babylon.
  75153. * A post process can be used to apply a shader to a texture after it is rendered.
  75154. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  75155. */
  75156. var PostProcessRenderEffect = /** @class */ (function () {
  75157. /**
  75158. * Instantiates a post process render effect.
  75159. * A post process can be used to apply a shader to a texture after it is rendered.
  75160. * @param engine The engine the effect is tied to
  75161. * @param name The name of the effect
  75162. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  75163. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  75164. */
  75165. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  75166. this._name = name;
  75167. this._singleInstance = singleInstance || true;
  75168. this._getPostProcesses = getPostProcesses;
  75169. this._cameras = {};
  75170. this._indicesForCamera = {};
  75171. this._postProcesses = {};
  75172. }
  75173. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  75174. /**
  75175. * Checks if all the post processes in the effect are supported.
  75176. */
  75177. get: function () {
  75178. for (var index in this._postProcesses) {
  75179. if (this._postProcesses.hasOwnProperty(index)) {
  75180. var pps = this._postProcesses[index];
  75181. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  75182. if (!pps[ppIndex].isSupported) {
  75183. return false;
  75184. }
  75185. }
  75186. }
  75187. }
  75188. return true;
  75189. },
  75190. enumerable: true,
  75191. configurable: true
  75192. });
  75193. /**
  75194. * Updates the current state of the effect
  75195. */
  75196. PostProcessRenderEffect.prototype._update = function () {
  75197. };
  75198. /**
  75199. * Attaches the effect on cameras
  75200. * @param cameras The camera to attach to.
  75201. */
  75202. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  75203. var _this = this;
  75204. var cameraKey;
  75205. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75206. if (!cams) {
  75207. return;
  75208. }
  75209. for (var i = 0; i < cams.length; i++) {
  75210. var camera = cams[i];
  75211. var cameraName = camera.name;
  75212. if (this._singleInstance) {
  75213. cameraKey = 0;
  75214. }
  75215. else {
  75216. cameraKey = cameraName;
  75217. }
  75218. if (!this._postProcesses[cameraKey]) {
  75219. var postProcess = this._getPostProcesses();
  75220. if (postProcess) {
  75221. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  75222. }
  75223. }
  75224. if (!this._indicesForCamera[cameraName]) {
  75225. this._indicesForCamera[cameraName] = [];
  75226. }
  75227. this._postProcesses[cameraKey].forEach(function (postProcess) {
  75228. var index = camera.attachPostProcess(postProcess);
  75229. _this._indicesForCamera[cameraName].push(index);
  75230. });
  75231. if (!this._cameras[cameraName]) {
  75232. this._cameras[cameraName] = camera;
  75233. }
  75234. }
  75235. };
  75236. /**
  75237. * Detatches the effect on cameras
  75238. * @param cameras The camera to detatch from.
  75239. */
  75240. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  75241. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75242. if (!cams) {
  75243. return;
  75244. }
  75245. for (var i = 0; i < cams.length; i++) {
  75246. var camera = cams[i];
  75247. var cameraName = camera.name;
  75248. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75249. camera.detachPostProcess(postProcess);
  75250. });
  75251. if (this._cameras[cameraName]) {
  75252. //this._indicesForCamera.splice(index, 1);
  75253. this._cameras[cameraName] = null;
  75254. }
  75255. }
  75256. };
  75257. /**
  75258. * Enables the effect on given cameras
  75259. * @param cameras The camera to enable.
  75260. */
  75261. PostProcessRenderEffect.prototype._enable = function (cameras) {
  75262. var _this = this;
  75263. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75264. if (!cams) {
  75265. return;
  75266. }
  75267. for (var i = 0; i < cams.length; i++) {
  75268. var camera = cams[i];
  75269. var cameraName = camera.name;
  75270. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  75271. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  75272. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75273. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  75274. });
  75275. }
  75276. }
  75277. }
  75278. };
  75279. /**
  75280. * Disables the effect on the given cameras
  75281. * @param cameras The camera to disable.
  75282. */
  75283. PostProcessRenderEffect.prototype._disable = function (cameras) {
  75284. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75285. if (!cams) {
  75286. return;
  75287. }
  75288. for (var i = 0; i < cams.length; i++) {
  75289. var camera = cams[i];
  75290. var cameraName = camera.name;
  75291. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75292. camera.detachPostProcess(postProcess);
  75293. });
  75294. }
  75295. };
  75296. /**
  75297. * Gets a list of the post processes contained in the effect.
  75298. * @param camera The camera to get the post processes on.
  75299. * @returns The list of the post processes in the effect.
  75300. */
  75301. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  75302. if (this._singleInstance) {
  75303. return this._postProcesses[0];
  75304. }
  75305. else {
  75306. if (!camera) {
  75307. return null;
  75308. }
  75309. return this._postProcesses[camera.name];
  75310. }
  75311. };
  75312. return PostProcessRenderEffect;
  75313. }());
  75314. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  75315. })(BABYLON || (BABYLON = {}));
  75316. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  75317. var BABYLON;
  75318. (function (BABYLON) {
  75319. var PostProcessRenderPipeline = /** @class */ (function () {
  75320. function PostProcessRenderPipeline(engine, name) {
  75321. this.engine = engine;
  75322. this._name = name;
  75323. this._renderEffects = {};
  75324. this._renderEffectsForIsolatedPass = new Array();
  75325. this._cameras = [];
  75326. }
  75327. PostProcessRenderPipeline.prototype.getClassName = function () {
  75328. return "PostProcessRenderPipeline";
  75329. };
  75330. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  75331. get: function () {
  75332. for (var renderEffectName in this._renderEffects) {
  75333. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75334. if (!this._renderEffects[renderEffectName].isSupported) {
  75335. return false;
  75336. }
  75337. }
  75338. }
  75339. return true;
  75340. },
  75341. enumerable: true,
  75342. configurable: true
  75343. });
  75344. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  75345. this._renderEffects[renderEffect._name] = renderEffect;
  75346. };
  75347. // private
  75348. PostProcessRenderPipeline.prototype._rebuild = function () {
  75349. };
  75350. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  75351. var renderEffects = this._renderEffects[renderEffectName];
  75352. if (!renderEffects) {
  75353. return;
  75354. }
  75355. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  75356. };
  75357. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  75358. var renderEffects = this._renderEffects[renderEffectName];
  75359. if (!renderEffects) {
  75360. return;
  75361. }
  75362. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  75363. };
  75364. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  75365. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75366. if (!cams) {
  75367. return;
  75368. }
  75369. var indicesToDelete = [];
  75370. var i;
  75371. for (i = 0; i < cams.length; i++) {
  75372. var camera = cams[i];
  75373. var cameraName = camera.name;
  75374. if (this._cameras.indexOf(camera) === -1) {
  75375. this._cameras[cameraName] = camera;
  75376. }
  75377. else if (unique) {
  75378. indicesToDelete.push(i);
  75379. }
  75380. }
  75381. for (i = 0; i < indicesToDelete.length; i++) {
  75382. cameras.splice(indicesToDelete[i], 1);
  75383. }
  75384. for (var renderEffectName in this._renderEffects) {
  75385. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75386. this._renderEffects[renderEffectName]._attachCameras(cams);
  75387. }
  75388. }
  75389. };
  75390. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  75391. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75392. if (!cams) {
  75393. return;
  75394. }
  75395. for (var renderEffectName in this._renderEffects) {
  75396. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75397. this._renderEffects[renderEffectName]._detachCameras(cams);
  75398. }
  75399. }
  75400. for (var i = 0; i < cams.length; i++) {
  75401. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  75402. }
  75403. };
  75404. PostProcessRenderPipeline.prototype._update = function () {
  75405. for (var renderEffectName in this._renderEffects) {
  75406. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75407. this._renderEffects[renderEffectName]._update();
  75408. }
  75409. }
  75410. for (var i = 0; i < this._cameras.length; i++) {
  75411. var cameraName = this._cameras[i].name;
  75412. if (this._renderEffectsForIsolatedPass[cameraName]) {
  75413. this._renderEffectsForIsolatedPass[cameraName]._update();
  75414. }
  75415. }
  75416. };
  75417. PostProcessRenderPipeline.prototype._reset = function () {
  75418. this._renderEffects = {};
  75419. this._renderEffectsForIsolatedPass = new Array();
  75420. };
  75421. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  75422. // 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)
  75423. var effectKeys = Object.keys(this._renderEffects);
  75424. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  75425. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  75426. if (postProcesses) {
  75427. postProcesses[0].samples = sampleCount;
  75428. return true;
  75429. }
  75430. }
  75431. return false;
  75432. };
  75433. PostProcessRenderPipeline.prototype.dispose = function () {
  75434. // Must be implemented by children
  75435. };
  75436. __decorate([
  75437. BABYLON.serialize()
  75438. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  75439. return PostProcessRenderPipeline;
  75440. }());
  75441. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  75442. })(BABYLON || (BABYLON = {}));
  75443. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  75444. var BABYLON;
  75445. (function (BABYLON) {
  75446. /**
  75447. * This represents a depth renderer in Babylon.
  75448. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  75449. */
  75450. var DepthRenderer = /** @class */ (function () {
  75451. /**
  75452. * Instantiates a depth renderer
  75453. * @param scene The scene the renderer belongs to
  75454. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  75455. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  75456. */
  75457. function DepthRenderer(scene, type, camera) {
  75458. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  75459. if (camera === void 0) { camera = null; }
  75460. var _this = this;
  75461. this._scene = scene;
  75462. this._camera = camera;
  75463. var engine = scene.getEngine();
  75464. // Render target
  75465. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  75466. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75467. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75468. this._depthMap.refreshRate = 1;
  75469. this._depthMap.renderParticles = false;
  75470. this._depthMap.renderList = null;
  75471. // Camera to get depth map from to support multiple concurrent cameras
  75472. this._depthMap.activeCamera = this._camera;
  75473. this._depthMap.ignoreCameraViewport = true;
  75474. this._depthMap.useCameraPostProcesses = false;
  75475. // set default depth value to 1.0 (far away)
  75476. this._depthMap.onClearObservable.add(function (engine) {
  75477. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  75478. });
  75479. // Custom render function
  75480. var renderSubMesh = function (subMesh) {
  75481. var mesh = subMesh.getRenderingMesh();
  75482. var scene = _this._scene;
  75483. var engine = scene.getEngine();
  75484. var material = subMesh.getMaterial();
  75485. if (!material) {
  75486. return;
  75487. }
  75488. // Culling and reverse (right handed system)
  75489. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75490. // Managing instances
  75491. var batch = mesh._getInstancesRenderList(subMesh._id);
  75492. if (batch.mustReturn) {
  75493. return;
  75494. }
  75495. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75496. var camera = _this._camera || scene.activeCamera;
  75497. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  75498. engine.enableEffect(_this._effect);
  75499. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75500. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75501. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  75502. // Alpha test
  75503. if (material && material.needAlphaTesting()) {
  75504. var alphaTexture = material.getAlphaTestTexture();
  75505. if (alphaTexture) {
  75506. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75507. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75508. }
  75509. }
  75510. // Bones
  75511. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75512. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75513. }
  75514. // Draw
  75515. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75516. }
  75517. };
  75518. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75519. var index;
  75520. if (depthOnlySubMeshes.length) {
  75521. engine.setColorWrite(false);
  75522. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75523. renderSubMesh(depthOnlySubMeshes.data[index]);
  75524. }
  75525. engine.setColorWrite(true);
  75526. }
  75527. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75528. renderSubMesh(opaqueSubMeshes.data[index]);
  75529. }
  75530. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75531. renderSubMesh(alphaTestSubMeshes.data[index]);
  75532. }
  75533. };
  75534. }
  75535. /**
  75536. * Creates the depth rendering effect and checks if the effect is ready.
  75537. * @param subMesh The submesh to be used to render the depth map of
  75538. * @param useInstances If multiple world instances should be used
  75539. * @returns if the depth renderer is ready to render the depth map
  75540. */
  75541. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  75542. var material = subMesh.getMaterial();
  75543. if (material.disableDepthWrite) {
  75544. return false;
  75545. }
  75546. var defines = [];
  75547. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75548. var mesh = subMesh.getMesh();
  75549. // Alpha test
  75550. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  75551. defines.push("#define ALPHATEST");
  75552. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75553. attribs.push(BABYLON.VertexBuffer.UVKind);
  75554. defines.push("#define UV1");
  75555. }
  75556. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75557. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75558. defines.push("#define UV2");
  75559. }
  75560. }
  75561. // Bones
  75562. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75563. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75564. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75565. if (mesh.numBoneInfluencers > 4) {
  75566. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75567. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75568. }
  75569. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75570. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75571. }
  75572. else {
  75573. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75574. }
  75575. // Instances
  75576. if (useInstances) {
  75577. defines.push("#define INSTANCES");
  75578. attribs.push("world0");
  75579. attribs.push("world1");
  75580. attribs.push("world2");
  75581. attribs.push("world3");
  75582. }
  75583. // Get correct effect
  75584. var join = defines.join("\n");
  75585. if (this._cachedDefines !== join) {
  75586. this._cachedDefines = join;
  75587. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  75588. }
  75589. return this._effect.isReady();
  75590. };
  75591. /**
  75592. * Gets the texture which the depth map will be written to.
  75593. * @returns The depth map texture
  75594. */
  75595. DepthRenderer.prototype.getDepthMap = function () {
  75596. return this._depthMap;
  75597. };
  75598. /**
  75599. * Disposes of the depth renderer.
  75600. */
  75601. DepthRenderer.prototype.dispose = function () {
  75602. this._depthMap.dispose();
  75603. };
  75604. return DepthRenderer;
  75605. }());
  75606. BABYLON.DepthRenderer = DepthRenderer;
  75607. })(BABYLON || (BABYLON = {}));
  75608. //# sourceMappingURL=babylon.depthRenderer.js.map
  75609. var BABYLON;
  75610. (function (BABYLON) {
  75611. var SSAORenderingPipeline = /** @class */ (function (_super) {
  75612. __extends(SSAORenderingPipeline, _super);
  75613. /**
  75614. * @constructor
  75615. * @param {string} name - The rendering pipeline name
  75616. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75617. * @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 }
  75618. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75619. */
  75620. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  75621. var _this = _super.call(this, scene.getEngine(), name) || this;
  75622. // Members
  75623. /**
  75624. * The PassPostProcess id in the pipeline that contains the original scene color
  75625. */
  75626. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75627. /**
  75628. * The SSAO PostProcess id in the pipeline
  75629. */
  75630. _this.SSAORenderEffect = "SSAORenderEffect";
  75631. /**
  75632. * The horizontal blur PostProcess id in the pipeline
  75633. */
  75634. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75635. /**
  75636. * The vertical blur PostProcess id in the pipeline
  75637. */
  75638. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75639. /**
  75640. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75641. */
  75642. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75643. /**
  75644. * The output strength of the SSAO post-process. Default value is 1.0.
  75645. */
  75646. _this.totalStrength = 1.0;
  75647. /**
  75648. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  75649. */
  75650. _this.radius = 0.0001;
  75651. /**
  75652. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  75653. * Must not be equal to fallOff and superior to fallOff.
  75654. * Default value is 0.975
  75655. */
  75656. _this.area = 0.0075;
  75657. /**
  75658. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  75659. * Must not be equal to area and inferior to area.
  75660. * Default value is 0.0
  75661. */
  75662. _this.fallOff = 0.000001;
  75663. /**
  75664. * The base color of the SSAO post-process
  75665. * The final result is "base + ssao" between [0, 1]
  75666. */
  75667. _this.base = 0.5;
  75668. _this._firstUpdate = true;
  75669. _this._scene = scene;
  75670. // Set up assets
  75671. _this._createRandomTexture();
  75672. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75673. var ssaoRatio = ratio.ssaoRatio || ratio;
  75674. var combineRatio = ratio.combineRatio || ratio;
  75675. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75676. _this._createSSAOPostProcess(ssaoRatio);
  75677. _this._createBlurPostProcess(ssaoRatio);
  75678. _this._createSSAOCombinePostProcess(combineRatio);
  75679. // Set up pipeline
  75680. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75681. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75682. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75683. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75684. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75685. // Finish
  75686. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75687. if (cameras)
  75688. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75689. return _this;
  75690. }
  75691. // Public Methods
  75692. /**
  75693. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75694. */
  75695. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75696. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75697. for (var i = 0; i < this._scene.cameras.length; i++) {
  75698. var camera = this._scene.cameras[i];
  75699. this._originalColorPostProcess.dispose(camera);
  75700. this._ssaoPostProcess.dispose(camera);
  75701. this._blurHPostProcess.dispose(camera);
  75702. this._blurVPostProcess.dispose(camera);
  75703. this._ssaoCombinePostProcess.dispose(camera);
  75704. }
  75705. this._randomTexture.dispose();
  75706. if (disableDepthRender)
  75707. this._scene.disableDepthRenderer();
  75708. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75709. _super.prototype.dispose.call(this);
  75710. };
  75711. // Private Methods
  75712. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  75713. var _this = this;
  75714. var size = 16;
  75715. 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);
  75716. 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);
  75717. this._blurHPostProcess.onActivateObservable.add(function () {
  75718. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  75719. _this._blurHPostProcess.kernel = size * dw;
  75720. });
  75721. this._blurVPostProcess.onActivateObservable.add(function () {
  75722. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  75723. _this._blurVPostProcess.kernel = size * dw;
  75724. });
  75725. };
  75726. SSAORenderingPipeline.prototype._rebuild = function () {
  75727. this._firstUpdate = true;
  75728. _super.prototype._rebuild.call(this);
  75729. };
  75730. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75731. var _this = this;
  75732. var numSamples = 16;
  75733. var sampleSphere = [
  75734. 0.5381, 0.1856, -0.4319,
  75735. 0.1379, 0.2486, 0.4430,
  75736. 0.3371, 0.5679, -0.0057,
  75737. -0.6999, -0.0451, -0.0019,
  75738. 0.0689, -0.1598, -0.8547,
  75739. 0.0560, 0.0069, -0.1843,
  75740. -0.0146, 0.1402, 0.0762,
  75741. 0.0100, -0.1924, -0.0344,
  75742. -0.3577, -0.5301, -0.4358,
  75743. -0.3169, 0.1063, 0.0158,
  75744. 0.0103, -0.5869, 0.0046,
  75745. -0.0897, -0.4940, 0.3287,
  75746. 0.7119, -0.0154, -0.0918,
  75747. -0.0533, 0.0596, -0.5411,
  75748. 0.0352, -0.0631, 0.5460,
  75749. -0.4776, 0.2847, -0.0271
  75750. ];
  75751. var samplesFactor = 1.0 / numSamples;
  75752. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  75753. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75754. "area", "fallOff", "base", "range", "viewport"
  75755. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75756. this._ssaoPostProcess.onApply = function (effect) {
  75757. if (_this._firstUpdate) {
  75758. effect.setArray3("sampleSphere", sampleSphere);
  75759. effect.setFloat("samplesFactor", samplesFactor);
  75760. effect.setFloat("randTextureTiles", 4.0);
  75761. }
  75762. effect.setFloat("totalStrength", _this.totalStrength);
  75763. effect.setFloat("radius", _this.radius);
  75764. effect.setFloat("area", _this.area);
  75765. effect.setFloat("fallOff", _this.fallOff);
  75766. effect.setFloat("base", _this.base);
  75767. effect.setTexture("textureSampler", _this._depthTexture);
  75768. effect.setTexture("randomSampler", _this._randomTexture);
  75769. };
  75770. };
  75771. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75772. var _this = this;
  75773. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75774. this._ssaoCombinePostProcess.onApply = function (effect) {
  75775. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  75776. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75777. };
  75778. };
  75779. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  75780. var size = 512;
  75781. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75782. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75783. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75784. var context = this._randomTexture.getContext();
  75785. var rand = function (min, max) {
  75786. return Math.random() * (max - min) + min;
  75787. };
  75788. var randVector = BABYLON.Vector3.Zero();
  75789. for (var x = 0; x < size; x++) {
  75790. for (var y = 0; y < size; y++) {
  75791. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  75792. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  75793. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  75794. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75795. context.fillRect(x, y, 1, 1);
  75796. }
  75797. }
  75798. this._randomTexture.update(false);
  75799. };
  75800. __decorate([
  75801. BABYLON.serialize()
  75802. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  75803. __decorate([
  75804. BABYLON.serialize()
  75805. ], SSAORenderingPipeline.prototype, "radius", void 0);
  75806. __decorate([
  75807. BABYLON.serialize()
  75808. ], SSAORenderingPipeline.prototype, "area", void 0);
  75809. __decorate([
  75810. BABYLON.serialize()
  75811. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  75812. __decorate([
  75813. BABYLON.serialize()
  75814. ], SSAORenderingPipeline.prototype, "base", void 0);
  75815. return SSAORenderingPipeline;
  75816. }(BABYLON.PostProcessRenderPipeline));
  75817. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  75818. })(BABYLON || (BABYLON = {}));
  75819. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  75820. var BABYLON;
  75821. (function (BABYLON) {
  75822. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  75823. __extends(SSAO2RenderingPipeline, _super);
  75824. /**
  75825. * @constructor
  75826. * @param {string} name - The rendering pipeline name
  75827. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75828. * @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 }
  75829. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75830. */
  75831. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  75832. var _this = _super.call(this, scene.getEngine(), name) || this;
  75833. // Members
  75834. /**
  75835. * The PassPostProcess id in the pipeline that contains the original scene color
  75836. */
  75837. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75838. /**
  75839. * The SSAO PostProcess id in the pipeline
  75840. */
  75841. _this.SSAORenderEffect = "SSAORenderEffect";
  75842. /**
  75843. * The horizontal blur PostProcess id in the pipeline
  75844. */
  75845. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75846. /**
  75847. * The vertical blur PostProcess id in the pipeline
  75848. */
  75849. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75850. /**
  75851. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75852. */
  75853. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75854. /**
  75855. * The output strength of the SSAO post-process. Default value is 1.0.
  75856. */
  75857. _this.totalStrength = 1.0;
  75858. /**
  75859. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  75860. */
  75861. _this.maxZ = 100.0;
  75862. /**
  75863. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  75864. */
  75865. _this.minZAspect = 0.2;
  75866. /**
  75867. * Number of samples used for the SSAO calculations. Default value is 8
  75868. */
  75869. _this._samples = 8;
  75870. /**
  75871. * Are we using bilateral blur ?
  75872. */
  75873. _this._expensiveBlur = true;
  75874. /**
  75875. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  75876. */
  75877. _this.radius = 2.0;
  75878. /**
  75879. * The base color of the SSAO post-process
  75880. * The final result is "base + ssao" between [0, 1]
  75881. */
  75882. _this.base = 0.1;
  75883. _this._firstUpdate = true;
  75884. _this._scene = scene;
  75885. _this._ratio = ratio;
  75886. if (!_this.isSupported) {
  75887. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  75888. return _this;
  75889. }
  75890. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  75891. var blurRatio = _this._ratio.blurRatio || ratio;
  75892. // Set up assets
  75893. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  75894. _this._createRandomTexture();
  75895. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  75896. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  75897. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75898. _this._createSSAOPostProcess(1.0);
  75899. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  75900. _this._createSSAOCombinePostProcess(blurRatio);
  75901. // Set up pipeline
  75902. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75903. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75904. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75906. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75907. // Finish
  75908. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75909. if (cameras)
  75910. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75911. return _this;
  75912. }
  75913. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  75914. get: function () {
  75915. return this._samples;
  75916. },
  75917. set: function (n) {
  75918. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  75919. this._samples = n;
  75920. this._sampleSphere = this._generateHemisphere();
  75921. this._firstUpdate = true;
  75922. },
  75923. enumerable: true,
  75924. configurable: true
  75925. });
  75926. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  75927. get: function () {
  75928. return this._expensiveBlur;
  75929. },
  75930. set: function (b) {
  75931. 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"]);
  75932. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  75933. this._expensiveBlur = b;
  75934. this._firstUpdate = true;
  75935. },
  75936. enumerable: true,
  75937. configurable: true
  75938. });
  75939. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  75940. /**
  75941. * Support test.
  75942. */
  75943. get: function () {
  75944. var engine = BABYLON.Engine.LastCreatedEngine;
  75945. if (!engine) {
  75946. return false;
  75947. }
  75948. return engine.getCaps().drawBuffersExtension;
  75949. },
  75950. enumerable: true,
  75951. configurable: true
  75952. });
  75953. // Public Methods
  75954. /**
  75955. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75956. */
  75957. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  75958. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  75959. for (var i = 0; i < this._scene.cameras.length; i++) {
  75960. var camera = this._scene.cameras[i];
  75961. this._originalColorPostProcess.dispose(camera);
  75962. this._ssaoPostProcess.dispose(camera);
  75963. this._blurHPostProcess.dispose(camera);
  75964. this._blurVPostProcess.dispose(camera);
  75965. this._ssaoCombinePostProcess.dispose(camera);
  75966. }
  75967. this._randomTexture.dispose();
  75968. if (disableGeometryBufferRenderer)
  75969. this._scene.disableGeometryBufferRenderer();
  75970. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75971. _super.prototype.dispose.call(this);
  75972. };
  75973. // Private Methods
  75974. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  75975. var _this = this;
  75976. this._samplerOffsets = [];
  75977. var expensive = this.expensiveBlur;
  75978. for (var i = -8; i < 8; i++) {
  75979. this._samplerOffsets.push(i * 2 + 0.5);
  75980. }
  75981. 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");
  75982. this._blurHPostProcess.onApply = function (effect) {
  75983. if (!_this._scene.activeCamera) {
  75984. return;
  75985. }
  75986. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  75987. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75988. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75989. effect.setFloat("radius", _this.radius);
  75990. effect.setTexture("depthSampler", _this._depthTexture);
  75991. if (_this._firstUpdate) {
  75992. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75993. }
  75994. };
  75995. 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");
  75996. this._blurVPostProcess.onApply = function (effect) {
  75997. if (!_this._scene.activeCamera) {
  75998. return;
  75999. }
  76000. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  76001. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76002. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76003. effect.setFloat("radius", _this.radius);
  76004. effect.setTexture("depthSampler", _this._depthTexture);
  76005. if (_this._firstUpdate) {
  76006. effect.setArray("samplerOffsets", _this._samplerOffsets);
  76007. _this._firstUpdate = false;
  76008. }
  76009. };
  76010. };
  76011. SSAO2RenderingPipeline.prototype._rebuild = function () {
  76012. this._firstUpdate = true;
  76013. _super.prototype._rebuild.call(this);
  76014. };
  76015. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  76016. var numSamples = this.samples;
  76017. var result = [];
  76018. var vector, scale;
  76019. var rand = function (min, max) {
  76020. return Math.random() * (max - min) + min;
  76021. };
  76022. var i = 0;
  76023. while (i < numSamples) {
  76024. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  76025. vector.normalize();
  76026. scale = i / numSamples;
  76027. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  76028. vector.scaleInPlace(scale);
  76029. result.push(vector.x, vector.y, vector.z);
  76030. i++;
  76031. }
  76032. return result;
  76033. };
  76034. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  76035. var _this = this;
  76036. var numSamples = this.samples;
  76037. this._sampleSphere = this._generateHemisphere();
  76038. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  76039. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  76040. "base", "range", "projection", "near", "far", "texelSize",
  76041. "xViewport", "yViewport", "maxZ", "minZAspect"
  76042. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  76043. this._ssaoPostProcess.onApply = function (effect) {
  76044. if (_this._firstUpdate) {
  76045. effect.setArray3("sampleSphere", _this._sampleSphere);
  76046. effect.setFloat("randTextureTiles", 4.0);
  76047. }
  76048. if (!_this._scene.activeCamera) {
  76049. return;
  76050. }
  76051. effect.setFloat("samplesFactor", 1 / _this.samples);
  76052. effect.setFloat("totalStrength", _this.totalStrength);
  76053. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  76054. effect.setFloat("radius", _this.radius);
  76055. effect.setFloat("maxZ", _this.maxZ);
  76056. effect.setFloat("minZAspect", _this.minZAspect);
  76057. effect.setFloat("base", _this.base);
  76058. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76059. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76060. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  76061. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  76062. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  76063. effect.setTexture("textureSampler", _this._depthTexture);
  76064. effect.setTexture("normalSampler", _this._normalTexture);
  76065. effect.setTexture("randomSampler", _this._randomTexture);
  76066. };
  76067. };
  76068. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  76069. var _this = this;
  76070. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76071. this._ssaoCombinePostProcess.onApply = function (effect) {
  76072. var viewport = _this._scene.activeCamera.viewport;
  76073. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  76074. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  76075. };
  76076. };
  76077. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  76078. var size = 512;
  76079. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76080. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76081. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76082. var context = this._randomTexture.getContext();
  76083. var rand = function (min, max) {
  76084. return Math.random() * (max - min) + min;
  76085. };
  76086. var randVector = BABYLON.Vector3.Zero();
  76087. for (var x = 0; x < size; x++) {
  76088. for (var y = 0; y < size; y++) {
  76089. randVector.x = rand(0.0, 1.0);
  76090. randVector.y = rand(0.0, 1.0);
  76091. randVector.z = 0.0;
  76092. randVector.normalize();
  76093. randVector.scaleInPlace(255);
  76094. randVector.x = Math.floor(randVector.x);
  76095. randVector.y = Math.floor(randVector.y);
  76096. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  76097. context.fillRect(x, y, 1, 1);
  76098. }
  76099. }
  76100. this._randomTexture.update(false);
  76101. };
  76102. /**
  76103. * Serialize the rendering pipeline (Used when exporting)
  76104. * @returns the serialized object
  76105. */
  76106. SSAO2RenderingPipeline.prototype.serialize = function () {
  76107. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76108. serializationObject.customType = "SSAO2RenderingPipeline";
  76109. return serializationObject;
  76110. };
  76111. /**
  76112. * Parse the serialized pipeline
  76113. * @param source Source pipeline.
  76114. * @param scene The scene to load the pipeline to.
  76115. * @param rootUrl The URL of the serialized pipeline.
  76116. * @returns An instantiated pipeline from the serialized object.
  76117. */
  76118. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  76119. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76120. };
  76121. __decorate([
  76122. BABYLON.serialize()
  76123. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  76124. __decorate([
  76125. BABYLON.serialize()
  76126. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  76127. __decorate([
  76128. BABYLON.serialize()
  76129. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  76130. __decorate([
  76131. BABYLON.serialize("samples")
  76132. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  76133. __decorate([
  76134. BABYLON.serialize()
  76135. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  76136. __decorate([
  76137. BABYLON.serialize("expensiveBlur")
  76138. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  76139. __decorate([
  76140. BABYLON.serialize()
  76141. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  76142. __decorate([
  76143. BABYLON.serialize()
  76144. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  76145. return SSAO2RenderingPipeline;
  76146. }(BABYLON.PostProcessRenderPipeline));
  76147. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  76148. })(BABYLON || (BABYLON = {}));
  76149. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  76150. // BABYLON.JS Chromatic Aberration GLSL Shader
  76151. // Author: Olivier Guyot
  76152. // Separates very slightly R, G and B colors on the edges of the screen
  76153. // Inspired by Francois Tarlier & Martins Upitis
  76154. var BABYLON;
  76155. (function (BABYLON) {
  76156. var LensRenderingPipeline = /** @class */ (function (_super) {
  76157. __extends(LensRenderingPipeline, _super);
  76158. /**
  76159. * @constructor
  76160. *
  76161. * Effect parameters are as follow:
  76162. * {
  76163. * chromatic_aberration: number; // from 0 to x (1 for realism)
  76164. * edge_blur: number; // from 0 to x (1 for realism)
  76165. * distortion: number; // from 0 to x (1 for realism)
  76166. * grain_amount: number; // from 0 to 1
  76167. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  76168. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  76169. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  76170. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  76171. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  76172. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  76173. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  76174. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  76175. * }
  76176. * Note: if an effect parameter is unset, effect is disabled
  76177. *
  76178. * @param {string} name - The rendering pipeline name
  76179. * @param {object} parameters - An object containing all parameters (see above)
  76180. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76181. * @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)
  76182. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76183. */
  76184. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  76185. if (ratio === void 0) { ratio = 1.0; }
  76186. var _this = _super.call(this, scene.getEngine(), name) || this;
  76187. // Lens effects can be of the following:
  76188. // - chromatic aberration (slight shift of RGB colors)
  76189. // - blur on the edge of the lens
  76190. // - lens distortion
  76191. // - depth-of-field blur & highlights enhancing
  76192. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  76193. // - grain effect (noise or custom texture)
  76194. // Two additional texture samplers are needed:
  76195. // - depth map (for depth-of-field)
  76196. // - grain texture
  76197. /**
  76198. * The chromatic aberration PostProcess id in the pipeline
  76199. */
  76200. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  76201. /**
  76202. * The highlights enhancing PostProcess id in the pipeline
  76203. */
  76204. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  76205. /**
  76206. * The depth-of-field PostProcess id in the pipeline
  76207. */
  76208. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  76209. _this._scene = scene;
  76210. // Fetch texture samplers
  76211. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  76212. if (parameters.grain_texture) {
  76213. _this._grainTexture = parameters.grain_texture;
  76214. }
  76215. else {
  76216. _this._createGrainTexture();
  76217. }
  76218. // save parameters
  76219. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  76220. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  76221. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  76222. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  76223. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  76224. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  76225. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  76226. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  76227. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  76228. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  76229. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  76230. // Create effects
  76231. _this._createChromaticAberrationPostProcess(ratio);
  76232. _this._createHighlightsPostProcess(ratio);
  76233. _this._createDepthOfFieldPostProcess(ratio / 4);
  76234. // Set up pipeline
  76235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  76236. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  76237. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  76238. if (_this._highlightsGain === -1) {
  76239. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  76240. }
  76241. // Finish
  76242. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76243. if (cameras) {
  76244. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76245. }
  76246. return _this;
  76247. }
  76248. // public methods (self explanatory)
  76249. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  76250. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  76251. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  76252. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  76253. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  76254. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  76255. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  76256. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  76257. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  76258. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  76259. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  76260. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  76261. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  76262. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  76263. };
  76264. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  76265. this._highlightsPostProcess.updateEffect();
  76266. };
  76267. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  76268. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  76269. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  76270. this._highlightsGain = amount;
  76271. };
  76272. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  76273. if (this._highlightsGain === -1) {
  76274. this._highlightsGain = 1.0;
  76275. }
  76276. this._highlightsThreshold = amount;
  76277. };
  76278. LensRenderingPipeline.prototype.disableHighlights = function () {
  76279. this._highlightsGain = -1;
  76280. };
  76281. /**
  76282. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  76283. */
  76284. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  76285. if (disableDepthRender === void 0) { disableDepthRender = false; }
  76286. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76287. this._chromaticAberrationPostProcess = null;
  76288. this._highlightsPostProcess = null;
  76289. this._depthOfFieldPostProcess = null;
  76290. this._grainTexture.dispose();
  76291. if (disableDepthRender)
  76292. this._scene.disableDepthRenderer();
  76293. };
  76294. // colors shifting and distortion
  76295. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  76296. var _this = this;
  76297. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  76298. [], // samplers
  76299. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76300. this._chromaticAberrationPostProcess.onApply = function (effect) {
  76301. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  76302. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76303. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76304. effect.setFloat('radialIntensity', 1);
  76305. effect.setFloat2('direction', 17, 17);
  76306. effect.setFloat2('centerPosition', 0.5, 0.5);
  76307. };
  76308. };
  76309. // highlights enhancing
  76310. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  76311. var _this = this;
  76312. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  76313. [], // samplers
  76314. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  76315. this._highlightsPostProcess.onApply = function (effect) {
  76316. effect.setFloat('gain', _this._highlightsGain);
  76317. effect.setFloat('threshold', _this._highlightsThreshold);
  76318. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  76319. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76320. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76321. };
  76322. };
  76323. // colors shifting and distortion
  76324. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  76325. var _this = this;
  76326. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  76327. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  76328. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  76329. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76330. this._depthOfFieldPostProcess.onApply = function (effect) {
  76331. effect.setTexture("depthSampler", _this._depthTexture);
  76332. effect.setTexture("grainSampler", _this._grainTexture);
  76333. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  76334. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  76335. effect.setFloat('grain_amount', _this._grainAmount);
  76336. effect.setBool('blur_noise', _this._blurNoise);
  76337. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76338. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76339. effect.setFloat('distortion', _this._distortion);
  76340. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  76341. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  76342. effect.setFloat('aperture', _this._dofAperture);
  76343. effect.setFloat('darken', _this._dofDarken);
  76344. effect.setFloat('edge_blur', _this._edgeBlur);
  76345. effect.setBool('highlights', (_this._highlightsGain !== -1));
  76346. if (_this._scene.activeCamera) {
  76347. effect.setFloat('near', _this._scene.activeCamera.minZ);
  76348. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  76349. }
  76350. };
  76351. };
  76352. // creates a black and white random noise texture, 512x512
  76353. LensRenderingPipeline.prototype._createGrainTexture = function () {
  76354. var size = 512;
  76355. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76356. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76357. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76358. var context = this._grainTexture.getContext();
  76359. var rand = function (min, max) {
  76360. return Math.random() * (max - min) + min;
  76361. };
  76362. var value;
  76363. for (var x = 0; x < size; x++) {
  76364. for (var y = 0; y < size; y++) {
  76365. value = Math.floor(rand(0.42, 0.58) * 255);
  76366. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  76367. context.fillRect(x, y, 1, 1);
  76368. }
  76369. }
  76370. this._grainTexture.update(false);
  76371. };
  76372. return LensRenderingPipeline;
  76373. }(BABYLON.PostProcessRenderPipeline));
  76374. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  76375. })(BABYLON || (BABYLON = {}));
  76376. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  76377. var BABYLON;
  76378. (function (BABYLON) {
  76379. var StandardRenderingPipeline = /** @class */ (function (_super) {
  76380. __extends(StandardRenderingPipeline, _super);
  76381. /**
  76382. * @constructor
  76383. * @param {string} name - The rendering pipeline name
  76384. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76385. * @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)
  76386. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  76387. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76388. */
  76389. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  76390. if (originalPostProcess === void 0) { originalPostProcess = null; }
  76391. var _this = _super.call(this, scene.getEngine(), name) || this;
  76392. _this.downSampleX4PostProcess = null;
  76393. _this.brightPassPostProcess = null;
  76394. _this.blurHPostProcesses = [];
  76395. _this.blurVPostProcesses = [];
  76396. _this.textureAdderPostProcess = null;
  76397. _this.volumetricLightPostProcess = null;
  76398. _this.volumetricLightSmoothXPostProcess = null;
  76399. _this.volumetricLightSmoothYPostProcess = null;
  76400. _this.volumetricLightMergePostProces = null;
  76401. _this.volumetricLightFinalPostProcess = null;
  76402. _this.luminancePostProcess = null;
  76403. _this.luminanceDownSamplePostProcesses = [];
  76404. _this.hdrPostProcess = null;
  76405. _this.textureAdderFinalPostProcess = null;
  76406. _this.lensFlareFinalPostProcess = null;
  76407. _this.hdrFinalPostProcess = null;
  76408. _this.lensFlarePostProcess = null;
  76409. _this.lensFlareComposePostProcess = null;
  76410. _this.motionBlurPostProcess = null;
  76411. _this.depthOfFieldPostProcess = null;
  76412. // Values
  76413. _this.brightThreshold = 1.0;
  76414. _this.blurWidth = 512.0;
  76415. _this.horizontalBlur = false;
  76416. _this.exposure = 1.0;
  76417. _this.lensTexture = null;
  76418. _this.volumetricLightCoefficient = 0.2;
  76419. _this.volumetricLightPower = 4.0;
  76420. _this.volumetricLightBlurScale = 64.0;
  76421. _this.sourceLight = null;
  76422. _this.hdrMinimumLuminance = 1.0;
  76423. _this.hdrDecreaseRate = 0.5;
  76424. _this.hdrIncreaseRate = 0.5;
  76425. _this.lensColorTexture = null;
  76426. _this.lensFlareStrength = 20.0;
  76427. _this.lensFlareGhostDispersal = 1.4;
  76428. _this.lensFlareHaloWidth = 0.7;
  76429. _this.lensFlareDistortionStrength = 16.0;
  76430. _this.lensStarTexture = null;
  76431. _this.lensFlareDirtTexture = null;
  76432. _this.depthOfFieldDistance = 10.0;
  76433. _this.depthOfFieldBlurWidth = 64.0;
  76434. _this.motionStrength = 1.0;
  76435. // IAnimatable
  76436. _this.animations = [];
  76437. _this._currentDepthOfFieldSource = null;
  76438. _this._hdrCurrentLuminance = 1.0;
  76439. // Getters and setters
  76440. _this._bloomEnabled = true;
  76441. _this._depthOfFieldEnabled = false;
  76442. _this._vlsEnabled = false;
  76443. _this._lensFlareEnabled = false;
  76444. _this._hdrEnabled = false;
  76445. _this._motionBlurEnabled = false;
  76446. _this._motionBlurSamples = 64.0;
  76447. _this._volumetricLightStepsCount = 50.0;
  76448. _this._cameras = cameras || [];
  76449. // Initialize
  76450. _this._scene = scene;
  76451. _this._basePostProcess = originalPostProcess;
  76452. _this._ratio = ratio;
  76453. // Misc
  76454. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76455. // Finish
  76456. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76457. _this._buildPipeline();
  76458. return _this;
  76459. }
  76460. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  76461. get: function () {
  76462. return this._bloomEnabled;
  76463. },
  76464. set: function (enabled) {
  76465. if (this._bloomEnabled === enabled) {
  76466. return;
  76467. }
  76468. this._bloomEnabled = enabled;
  76469. this._buildPipeline();
  76470. },
  76471. enumerable: true,
  76472. configurable: true
  76473. });
  76474. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  76475. get: function () {
  76476. return this._depthOfFieldEnabled;
  76477. },
  76478. set: function (enabled) {
  76479. if (this._depthOfFieldEnabled === enabled) {
  76480. return;
  76481. }
  76482. this._depthOfFieldEnabled = enabled;
  76483. this._buildPipeline();
  76484. },
  76485. enumerable: true,
  76486. configurable: true
  76487. });
  76488. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  76489. get: function () {
  76490. return this._lensFlareEnabled;
  76491. },
  76492. set: function (enabled) {
  76493. if (this._lensFlareEnabled === enabled) {
  76494. return;
  76495. }
  76496. this._lensFlareEnabled = enabled;
  76497. this._buildPipeline();
  76498. },
  76499. enumerable: true,
  76500. configurable: true
  76501. });
  76502. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  76503. get: function () {
  76504. return this._hdrEnabled;
  76505. },
  76506. set: function (enabled) {
  76507. if (this._hdrEnabled === enabled) {
  76508. return;
  76509. }
  76510. this._hdrEnabled = enabled;
  76511. this._buildPipeline();
  76512. },
  76513. enumerable: true,
  76514. configurable: true
  76515. });
  76516. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  76517. get: function () {
  76518. return this._vlsEnabled;
  76519. },
  76520. set: function (enabled) {
  76521. if (this._vlsEnabled === enabled) {
  76522. return;
  76523. }
  76524. if (enabled) {
  76525. var geometry = this._scene.enableGeometryBufferRenderer();
  76526. if (!geometry) {
  76527. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  76528. return;
  76529. }
  76530. }
  76531. this._vlsEnabled = enabled;
  76532. this._buildPipeline();
  76533. },
  76534. enumerable: true,
  76535. configurable: true
  76536. });
  76537. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  76538. get: function () {
  76539. return this._motionBlurEnabled;
  76540. },
  76541. set: function (enabled) {
  76542. if (this._motionBlurEnabled === enabled) {
  76543. return;
  76544. }
  76545. this._motionBlurEnabled = enabled;
  76546. this._buildPipeline();
  76547. },
  76548. enumerable: true,
  76549. configurable: true
  76550. });
  76551. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  76552. get: function () {
  76553. return this._volumetricLightStepsCount;
  76554. },
  76555. set: function (count) {
  76556. if (this.volumetricLightPostProcess) {
  76557. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  76558. }
  76559. this._volumetricLightStepsCount = count;
  76560. },
  76561. enumerable: true,
  76562. configurable: true
  76563. });
  76564. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  76565. get: function () {
  76566. return this._motionBlurSamples;
  76567. },
  76568. set: function (samples) {
  76569. if (this.motionBlurPostProcess) {
  76570. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  76571. }
  76572. this._motionBlurSamples = samples;
  76573. },
  76574. enumerable: true,
  76575. configurable: true
  76576. });
  76577. StandardRenderingPipeline.prototype._buildPipeline = function () {
  76578. var _this = this;
  76579. var ratio = this._ratio;
  76580. var scene = this._scene;
  76581. this._disposePostProcesses();
  76582. this._reset();
  76583. // Create pass post-process
  76584. if (!this._basePostProcess) {
  76585. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  76586. this.originalPostProcess.onApply = function (effect) {
  76587. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  76588. };
  76589. }
  76590. else {
  76591. this.originalPostProcess = this._basePostProcess;
  76592. }
  76593. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  76594. this._currentDepthOfFieldSource = this.originalPostProcess;
  76595. if (this._bloomEnabled) {
  76596. // Create down sample X4 post-process
  76597. this._createDownSampleX4PostProcess(scene, ratio / 2);
  76598. // Create bright pass post-process
  76599. this._createBrightPassPostProcess(scene, ratio / 2);
  76600. // Create gaussian blur post-processes (down sampling blurs)
  76601. this._createBlurPostProcesses(scene, ratio / 4, 1);
  76602. // Create texture adder post-process
  76603. this._createTextureAdderPostProcess(scene, ratio);
  76604. // Create depth-of-field source post-process
  76605. 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);
  76606. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  76607. }
  76608. if (this._vlsEnabled) {
  76609. // Create volumetric light
  76610. this._createVolumetricLightPostProcess(scene, ratio);
  76611. // Create volumetric light final post-process
  76612. 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);
  76613. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  76614. }
  76615. if (this._lensFlareEnabled) {
  76616. // Create lens flare post-process
  76617. this._createLensFlarePostProcess(scene, ratio);
  76618. // Create depth-of-field source post-process post lens-flare and disable it now
  76619. 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);
  76620. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  76621. }
  76622. if (this._hdrEnabled) {
  76623. // Create luminance
  76624. this._createLuminancePostProcesses(scene, this._floatTextureType);
  76625. // Create HDR
  76626. this._createHdrPostProcess(scene, ratio);
  76627. // Create depth-of-field source post-process post hdr and disable it now
  76628. 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);
  76629. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  76630. }
  76631. if (this._depthOfFieldEnabled) {
  76632. // Create gaussian blur used by depth-of-field
  76633. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  76634. // Create depth-of-field post-process
  76635. this._createDepthOfFieldPostProcess(scene, ratio);
  76636. }
  76637. if (this._motionBlurEnabled) {
  76638. // Create motion blur post-process
  76639. this._createMotionBlurPostProcess(scene, ratio);
  76640. }
  76641. if (this._cameras !== null) {
  76642. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76643. }
  76644. };
  76645. // Down Sample X4 Post-Processs
  76646. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  76647. var _this = this;
  76648. var downSampleX4Offsets = new Array(32);
  76649. 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);
  76650. this.downSampleX4PostProcess.onApply = function (effect) {
  76651. var id = 0;
  76652. var width = _this.downSampleX4PostProcess.width;
  76653. var height = _this.downSampleX4PostProcess.height;
  76654. for (var i = -2; i < 2; i++) {
  76655. for (var j = -2; j < 2; j++) {
  76656. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  76657. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  76658. id += 2;
  76659. }
  76660. }
  76661. effect.setArray2("dsOffsets", downSampleX4Offsets);
  76662. };
  76663. // Add to pipeline
  76664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  76665. };
  76666. // Brightpass Post-Process
  76667. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  76668. var _this = this;
  76669. var brightOffsets = new Array(8);
  76670. 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);
  76671. this.brightPassPostProcess.onApply = function (effect) {
  76672. var sU = (1.0 / _this.brightPassPostProcess.width);
  76673. var sV = (1.0 / _this.brightPassPostProcess.height);
  76674. brightOffsets[0] = -0.5 * sU;
  76675. brightOffsets[1] = 0.5 * sV;
  76676. brightOffsets[2] = 0.5 * sU;
  76677. brightOffsets[3] = 0.5 * sV;
  76678. brightOffsets[4] = -0.5 * sU;
  76679. brightOffsets[5] = -0.5 * sV;
  76680. brightOffsets[6] = 0.5 * sU;
  76681. brightOffsets[7] = -0.5 * sV;
  76682. effect.setArray2("dsOffsets", brightOffsets);
  76683. effect.setFloat("brightThreshold", _this.brightThreshold);
  76684. };
  76685. // Add to pipeline
  76686. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  76687. };
  76688. // Create blur H&V post-processes
  76689. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  76690. var _this = this;
  76691. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  76692. var engine = scene.getEngine();
  76693. 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);
  76694. 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);
  76695. blurX.onActivateObservable.add(function () {
  76696. var dw = blurX.width / engine.getRenderWidth();
  76697. blurX.kernel = _this[blurWidthKey] * dw;
  76698. });
  76699. blurY.onActivateObservable.add(function () {
  76700. var dw = blurY.height / engine.getRenderHeight();
  76701. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  76702. });
  76703. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  76704. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  76705. this.blurHPostProcesses.push(blurX);
  76706. this.blurVPostProcesses.push(blurY);
  76707. };
  76708. // Create texture adder post-process
  76709. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  76710. var _this = this;
  76711. 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);
  76712. this.textureAdderPostProcess.onApply = function (effect) {
  76713. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  76714. effect.setTexture("lensSampler", _this.lensTexture);
  76715. effect.setFloat("exposure", _this.exposure);
  76716. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  76717. };
  76718. // Add to pipeline
  76719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  76720. };
  76721. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  76722. var _this = this;
  76723. var geometryRenderer = scene.enableGeometryBufferRenderer();
  76724. geometryRenderer.enablePosition = true;
  76725. var geometry = geometryRenderer.getGBuffer();
  76726. // Base post-process
  76727. 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));
  76728. var depthValues = BABYLON.Vector2.Zero();
  76729. this.volumetricLightPostProcess.onApply = function (effect) {
  76730. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  76731. var generator = _this.sourceLight.getShadowGenerator();
  76732. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  76733. effect.setTexture("positionSampler", geometry.textures[2]);
  76734. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  76735. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  76736. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  76737. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  76738. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  76739. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  76740. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  76741. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  76742. effect.setVector2("depthValues", depthValues);
  76743. }
  76744. };
  76745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  76746. // Smooth
  76747. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  76748. // Merge
  76749. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  76750. this.volumetricLightMergePostProces.onApply = function (effect) {
  76751. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  76752. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  76753. };
  76754. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  76755. };
  76756. // Create luminance
  76757. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  76758. var _this = this;
  76759. // Create luminance
  76760. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  76761. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  76762. var offsets = [];
  76763. this.luminancePostProcess.onApply = function (effect) {
  76764. var sU = (1.0 / _this.luminancePostProcess.width);
  76765. var sV = (1.0 / _this.luminancePostProcess.height);
  76766. offsets[0] = -0.5 * sU;
  76767. offsets[1] = 0.5 * sV;
  76768. offsets[2] = 0.5 * sU;
  76769. offsets[3] = 0.5 * sV;
  76770. offsets[4] = -0.5 * sU;
  76771. offsets[5] = -0.5 * sV;
  76772. offsets[6] = 0.5 * sU;
  76773. offsets[7] = -0.5 * sV;
  76774. effect.setArray2("lumOffsets", offsets);
  76775. };
  76776. // Add to pipeline
  76777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  76778. // Create down sample luminance
  76779. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  76780. var size = Math.pow(3, i);
  76781. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  76782. if (i === 0) {
  76783. defines += "#define FINAL_DOWN_SAMPLER";
  76784. }
  76785. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  76786. this.luminanceDownSamplePostProcesses.push(postProcess);
  76787. }
  76788. // Create callbacks and add effects
  76789. var lastLuminance = this.luminancePostProcess;
  76790. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  76791. var downSampleOffsets = new Array(18);
  76792. pp.onApply = function (effect) {
  76793. if (!lastLuminance) {
  76794. return;
  76795. }
  76796. var id = 0;
  76797. for (var x = -1; x < 2; x++) {
  76798. for (var y = -1; y < 2; y++) {
  76799. downSampleOffsets[id] = x / lastLuminance.width;
  76800. downSampleOffsets[id + 1] = y / lastLuminance.height;
  76801. id += 2;
  76802. }
  76803. }
  76804. effect.setArray2("dsOffsets", downSampleOffsets);
  76805. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  76806. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76807. lastLuminance = _this.luminancePostProcess;
  76808. }
  76809. else {
  76810. lastLuminance = pp;
  76811. }
  76812. };
  76813. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76814. pp.onAfterRender = function (effect) {
  76815. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  76816. 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);
  76817. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  76818. };
  76819. }
  76820. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  76821. });
  76822. };
  76823. // Create HDR post-process
  76824. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  76825. var _this = this;
  76826. 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);
  76827. var outputLiminance = 1;
  76828. var time = 0;
  76829. var lastTime = 0;
  76830. this.hdrPostProcess.onApply = function (effect) {
  76831. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  76832. time += scene.getEngine().getDeltaTime();
  76833. if (outputLiminance < 0) {
  76834. outputLiminance = _this._hdrCurrentLuminance;
  76835. }
  76836. else {
  76837. var dt = (lastTime - time) / 1000.0;
  76838. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  76839. outputLiminance += _this.hdrDecreaseRate * dt;
  76840. }
  76841. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  76842. outputLiminance -= _this.hdrIncreaseRate * dt;
  76843. }
  76844. else {
  76845. outputLiminance = _this._hdrCurrentLuminance;
  76846. }
  76847. }
  76848. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  76849. effect.setFloat("averageLuminance", outputLiminance);
  76850. lastTime = time;
  76851. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  76852. };
  76853. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  76854. };
  76855. // Create lens flare post-process
  76856. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  76857. var _this = this;
  76858. 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);
  76859. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  76860. this._createBlurPostProcesses(scene, ratio / 4, 2);
  76861. 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);
  76862. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  76863. var resolution = new BABYLON.Vector2(0, 0);
  76864. // Lens flare
  76865. this.lensFlarePostProcess.onApply = function (effect) {
  76866. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  76867. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  76868. effect.setFloat("strength", _this.lensFlareStrength);
  76869. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  76870. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  76871. // Shift
  76872. resolution.x = _this.lensFlarePostProcess.width;
  76873. resolution.y = _this.lensFlarePostProcess.height;
  76874. effect.setVector2("resolution", resolution);
  76875. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  76876. };
  76877. // Compose
  76878. 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);
  76879. 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);
  76880. this.lensFlareComposePostProcess.onApply = function (effect) {
  76881. if (!_this._scene.activeCamera) {
  76882. return;
  76883. }
  76884. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76885. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  76886. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  76887. // Lens start rotation matrix
  76888. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  76889. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  76890. 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));
  76891. camRot *= 4.0;
  76892. 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);
  76893. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  76894. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  76895. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  76896. };
  76897. };
  76898. // Create depth-of-field post-process
  76899. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  76900. var _this = this;
  76901. 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);
  76902. this.depthOfFieldPostProcess.onApply = function (effect) {
  76903. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76904. effect.setTexture("depthSampler", _this._getDepthTexture());
  76905. effect.setFloat("distance", _this.depthOfFieldDistance);
  76906. };
  76907. // Add to pipeline
  76908. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  76909. };
  76910. // Create motion blur post-process
  76911. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  76912. var _this = this;
  76913. 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);
  76914. var motionScale = 0;
  76915. var prevViewProjection = BABYLON.Matrix.Identity();
  76916. var invViewProjection = BABYLON.Matrix.Identity();
  76917. var viewProjection = BABYLON.Matrix.Identity();
  76918. var screenSize = BABYLON.Vector2.Zero();
  76919. this.motionBlurPostProcess.onApply = function (effect) {
  76920. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  76921. viewProjection.invertToRef(invViewProjection);
  76922. effect.setMatrix("inverseViewProjection", invViewProjection);
  76923. effect.setMatrix("prevViewProjection", prevViewProjection);
  76924. prevViewProjection = viewProjection;
  76925. screenSize.x = _this.motionBlurPostProcess.width;
  76926. screenSize.y = _this.motionBlurPostProcess.height;
  76927. effect.setVector2("screenSize", screenSize);
  76928. motionScale = scene.getEngine().getFps() / 60.0;
  76929. effect.setFloat("motionScale", motionScale);
  76930. effect.setFloat("motionStrength", _this.motionStrength);
  76931. effect.setTexture("depthSampler", _this._getDepthTexture());
  76932. };
  76933. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  76934. };
  76935. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  76936. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  76937. var renderer = this._scene.enableGeometryBufferRenderer();
  76938. return renderer.getGBuffer().textures[0];
  76939. }
  76940. return this._scene.enableDepthRenderer().getDepthMap();
  76941. };
  76942. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  76943. for (var i = 0; i < this._cameras.length; i++) {
  76944. var camera = this._cameras[i];
  76945. if (this.originalPostProcess) {
  76946. this.originalPostProcess.dispose(camera);
  76947. }
  76948. if (this.downSampleX4PostProcess) {
  76949. this.downSampleX4PostProcess.dispose(camera);
  76950. }
  76951. if (this.brightPassPostProcess) {
  76952. this.brightPassPostProcess.dispose(camera);
  76953. }
  76954. if (this.textureAdderPostProcess) {
  76955. this.textureAdderPostProcess.dispose(camera);
  76956. }
  76957. if (this.textureAdderFinalPostProcess) {
  76958. this.textureAdderFinalPostProcess.dispose(camera);
  76959. }
  76960. if (this.volumetricLightPostProcess) {
  76961. this.volumetricLightPostProcess.dispose(camera);
  76962. }
  76963. if (this.volumetricLightSmoothXPostProcess) {
  76964. this.volumetricLightSmoothXPostProcess.dispose(camera);
  76965. }
  76966. if (this.volumetricLightSmoothYPostProcess) {
  76967. this.volumetricLightSmoothYPostProcess.dispose(camera);
  76968. }
  76969. if (this.volumetricLightMergePostProces) {
  76970. this.volumetricLightMergePostProces.dispose(camera);
  76971. }
  76972. if (this.volumetricLightFinalPostProcess) {
  76973. this.volumetricLightFinalPostProcess.dispose(camera);
  76974. }
  76975. if (this.lensFlarePostProcess) {
  76976. this.lensFlarePostProcess.dispose(camera);
  76977. }
  76978. if (this.lensFlareComposePostProcess) {
  76979. this.lensFlareComposePostProcess.dispose(camera);
  76980. }
  76981. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  76982. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  76983. }
  76984. if (this.luminancePostProcess) {
  76985. this.luminancePostProcess.dispose(camera);
  76986. }
  76987. if (this.hdrPostProcess) {
  76988. this.hdrPostProcess.dispose(camera);
  76989. }
  76990. if (this.hdrFinalPostProcess) {
  76991. this.hdrFinalPostProcess.dispose(camera);
  76992. }
  76993. if (this.depthOfFieldPostProcess) {
  76994. this.depthOfFieldPostProcess.dispose(camera);
  76995. }
  76996. if (this.motionBlurPostProcess) {
  76997. this.motionBlurPostProcess.dispose(camera);
  76998. }
  76999. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  77000. this.blurHPostProcesses[j].dispose(camera);
  77001. }
  77002. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  77003. this.blurVPostProcesses[j].dispose(camera);
  77004. }
  77005. }
  77006. this.originalPostProcess = null;
  77007. this.downSampleX4PostProcess = null;
  77008. this.brightPassPostProcess = null;
  77009. this.textureAdderPostProcess = null;
  77010. this.textureAdderFinalPostProcess = null;
  77011. this.volumetricLightPostProcess = null;
  77012. this.volumetricLightSmoothXPostProcess = null;
  77013. this.volumetricLightSmoothYPostProcess = null;
  77014. this.volumetricLightMergePostProces = null;
  77015. this.volumetricLightFinalPostProcess = null;
  77016. this.lensFlarePostProcess = null;
  77017. this.lensFlareComposePostProcess = null;
  77018. this.luminancePostProcess = null;
  77019. this.hdrPostProcess = null;
  77020. this.hdrFinalPostProcess = null;
  77021. this.depthOfFieldPostProcess = null;
  77022. this.motionBlurPostProcess = null;
  77023. this.luminanceDownSamplePostProcesses = [];
  77024. this.blurHPostProcesses = [];
  77025. this.blurVPostProcesses = [];
  77026. };
  77027. /**
  77028. * Dispose of the pipeline and stop all post processes
  77029. */
  77030. StandardRenderingPipeline.prototype.dispose = function () {
  77031. this._disposePostProcesses();
  77032. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77033. _super.prototype.dispose.call(this);
  77034. };
  77035. /**
  77036. * Serialize the rendering pipeline (Used when exporting)
  77037. * @returns the serialized object
  77038. */
  77039. StandardRenderingPipeline.prototype.serialize = function () {
  77040. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77041. if (this.sourceLight) {
  77042. serializationObject.sourceLightId = this.sourceLight.id;
  77043. }
  77044. serializationObject.customType = "StandardRenderingPipeline";
  77045. return serializationObject;
  77046. };
  77047. /**
  77048. * Parse the serialized pipeline
  77049. * @param source Source pipeline.
  77050. * @param scene The scene to load the pipeline to.
  77051. * @param rootUrl The URL of the serialized pipeline.
  77052. * @returns An instantiated pipeline from the serialized object.
  77053. */
  77054. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77055. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77056. if (source.sourceLightId) {
  77057. p.sourceLight = scene.getLightByID(source.sourceLightId);
  77058. }
  77059. return p;
  77060. };
  77061. // Luminance steps
  77062. StandardRenderingPipeline.LuminanceSteps = 6;
  77063. __decorate([
  77064. BABYLON.serialize()
  77065. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  77066. __decorate([
  77067. BABYLON.serialize()
  77068. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  77069. __decorate([
  77070. BABYLON.serialize()
  77071. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  77072. __decorate([
  77073. BABYLON.serialize()
  77074. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  77075. __decorate([
  77076. BABYLON.serializeAsTexture("lensTexture")
  77077. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  77078. __decorate([
  77079. BABYLON.serialize()
  77080. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  77081. __decorate([
  77082. BABYLON.serialize()
  77083. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  77084. __decorate([
  77085. BABYLON.serialize()
  77086. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  77087. __decorate([
  77088. BABYLON.serialize()
  77089. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  77090. __decorate([
  77091. BABYLON.serialize()
  77092. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  77093. __decorate([
  77094. BABYLON.serialize()
  77095. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  77096. __decorate([
  77097. BABYLON.serializeAsTexture("lensColorTexture")
  77098. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  77099. __decorate([
  77100. BABYLON.serialize()
  77101. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  77102. __decorate([
  77103. BABYLON.serialize()
  77104. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  77105. __decorate([
  77106. BABYLON.serialize()
  77107. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  77108. __decorate([
  77109. BABYLON.serialize()
  77110. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  77111. __decorate([
  77112. BABYLON.serializeAsTexture("lensStarTexture")
  77113. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  77114. __decorate([
  77115. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  77116. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  77117. __decorate([
  77118. BABYLON.serialize()
  77119. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  77120. __decorate([
  77121. BABYLON.serialize()
  77122. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  77123. __decorate([
  77124. BABYLON.serialize()
  77125. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  77126. __decorate([
  77127. BABYLON.serialize()
  77128. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  77129. __decorate([
  77130. BABYLON.serialize()
  77131. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  77132. __decorate([
  77133. BABYLON.serialize()
  77134. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  77135. __decorate([
  77136. BABYLON.serialize()
  77137. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  77138. __decorate([
  77139. BABYLON.serialize()
  77140. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  77141. __decorate([
  77142. BABYLON.serialize()
  77143. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  77144. __decorate([
  77145. BABYLON.serialize()
  77146. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  77147. __decorate([
  77148. BABYLON.serialize()
  77149. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  77150. __decorate([
  77151. BABYLON.serialize()
  77152. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  77153. return StandardRenderingPipeline;
  77154. }(BABYLON.PostProcessRenderPipeline));
  77155. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  77156. })(BABYLON || (BABYLON = {}));
  77157. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  77158. var BABYLON;
  77159. (function (BABYLON) {
  77160. var FxaaPostProcess = /** @class */ (function (_super) {
  77161. __extends(FxaaPostProcess, _super);
  77162. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77163. if (camera === void 0) { camera = null; }
  77164. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77165. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  77166. var defines = _this._getDefines();
  77167. _this.updateEffect(defines);
  77168. _this.onApplyObservable.add(function (effect) {
  77169. var texelSize = _this.texelSize;
  77170. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  77171. });
  77172. return _this;
  77173. }
  77174. FxaaPostProcess.prototype._getDefines = function () {
  77175. var engine = this.getEngine();
  77176. if (!engine) {
  77177. return null;
  77178. }
  77179. var glInfo = engine.getGlInfo();
  77180. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  77181. return "#define MALI 1\n";
  77182. }
  77183. return null;
  77184. };
  77185. return FxaaPostProcess;
  77186. }(BABYLON.PostProcess));
  77187. BABYLON.FxaaPostProcess = FxaaPostProcess;
  77188. })(BABYLON || (BABYLON = {}));
  77189. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  77190. var BABYLON;
  77191. (function (BABYLON) {
  77192. /**
  77193. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  77194. */
  77195. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  77196. __extends(ChromaticAberrationPostProcess, _super);
  77197. /**
  77198. * Creates a new instance ChromaticAberrationPostProcess
  77199. * @param name The name of the effect.
  77200. * @param screenWidth The width of the screen to apply the effect on.
  77201. * @param screenHeight The height of the screen to apply the effect on.
  77202. * @param options The required width/height ratio to downsize to before computing the render pass.
  77203. * @param camera The camera to apply the render pass to.
  77204. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77205. * @param engine The engine which the post process will be applied. (default: current engine)
  77206. * @param reusable If the post process can be reused on the same frame. (default: false)
  77207. * @param textureType Type of textures used when performing the post process. (default: 0)
  77208. * @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)
  77209. */
  77210. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77211. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77212. if (blockCompilation === void 0) { blockCompilation = false; }
  77213. 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;
  77214. /**
  77215. * The amount of seperation of rgb channels (default: 30)
  77216. */
  77217. _this.aberrationAmount = 30;
  77218. /**
  77219. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  77220. */
  77221. _this.radialIntensity = 0;
  77222. /**
  77223. * 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))
  77224. */
  77225. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  77226. /**
  77227. * 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))
  77228. */
  77229. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  77230. _this.onApplyObservable.add(function (effect) {
  77231. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  77232. effect.setFloat('screen_width', screenWidth);
  77233. effect.setFloat('screen_height', screenHeight);
  77234. effect.setFloat('radialIntensity', _this.radialIntensity);
  77235. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  77236. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  77237. });
  77238. return _this;
  77239. }
  77240. return ChromaticAberrationPostProcess;
  77241. }(BABYLON.PostProcess));
  77242. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  77243. })(BABYLON || (BABYLON = {}));
  77244. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  77245. var BABYLON;
  77246. (function (BABYLON) {
  77247. /**
  77248. * The GrainPostProcess adds noise to the image at mid luminance levels
  77249. */
  77250. var GrainPostProcess = /** @class */ (function (_super) {
  77251. __extends(GrainPostProcess, _super);
  77252. /**
  77253. * Creates a new instance of @see GrainPostProcess
  77254. * @param name The name of the effect.
  77255. * @param options The required width/height ratio to downsize to before computing the render pass.
  77256. * @param camera The camera to apply the render pass to.
  77257. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77258. * @param engine The engine which the post process will be applied. (default: current engine)
  77259. * @param reusable If the post process can be reused on the same frame. (default: false)
  77260. * @param textureType Type of textures used when performing the post process. (default: 0)
  77261. * @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)
  77262. */
  77263. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77264. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77265. if (blockCompilation === void 0) { blockCompilation = false; }
  77266. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77267. /**
  77268. * The intensity of the grain added (default: 30)
  77269. */
  77270. _this.intensity = 30;
  77271. /**
  77272. * If the grain should be randomized on every frame
  77273. */
  77274. _this.animated = false;
  77275. _this.onApplyObservable.add(function (effect) {
  77276. effect.setFloat('intensity', _this.intensity);
  77277. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  77278. });
  77279. return _this;
  77280. }
  77281. return GrainPostProcess;
  77282. }(BABYLON.PostProcess));
  77283. BABYLON.GrainPostProcess = GrainPostProcess;
  77284. })(BABYLON || (BABYLON = {}));
  77285. //# sourceMappingURL=babylon.grainPostProcess.js.map
  77286. var BABYLON;
  77287. (function (BABYLON) {
  77288. /**
  77289. * The SharpenPostProcess applies a sharpen kernel to every pixel
  77290. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77291. */
  77292. var SharpenPostProcess = /** @class */ (function (_super) {
  77293. __extends(SharpenPostProcess, _super);
  77294. /**
  77295. * Creates a new instance ConvolutionPostProcess
  77296. * @param name The name of the effect.
  77297. * @param options The required width/height ratio to downsize to before computing the render pass.
  77298. * @param camera The camera to apply the render pass to.
  77299. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77300. * @param engine The engine which the post process will be applied. (default: current engine)
  77301. * @param reusable If the post process can be reused on the same frame. (default: false)
  77302. * @param textureType Type of textures used when performing the post process. (default: 0)
  77303. * @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)
  77304. */
  77305. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77306. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77307. if (blockCompilation === void 0) { blockCompilation = false; }
  77308. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77309. /**
  77310. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  77311. */
  77312. _this.colorAmount = 1.0;
  77313. /**
  77314. * How much sharpness should be applied (default: 0.3)
  77315. */
  77316. _this.edgeAmount = 0.3;
  77317. _this.onApply = function (effect) {
  77318. effect.setFloat2("screenSize", _this.width, _this.height);
  77319. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  77320. };
  77321. return _this;
  77322. }
  77323. return SharpenPostProcess;
  77324. }(BABYLON.PostProcess));
  77325. BABYLON.SharpenPostProcess = SharpenPostProcess;
  77326. })(BABYLON || (BABYLON = {}));
  77327. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  77328. var BABYLON;
  77329. (function (BABYLON) {
  77330. /**
  77331. * The Blur Post Process which blurs an image based on a kernel and direction.
  77332. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  77333. */
  77334. var BlurPostProcess = /** @class */ (function (_super) {
  77335. __extends(BlurPostProcess, _super);
  77336. /**
  77337. * Creates a new instance BlurPostProcess
  77338. * @param name The name of the effect.
  77339. * @param direction The direction in which to blur the image.
  77340. * @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.
  77341. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  77342. * @param camera The camera to apply the render pass to.
  77343. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77344. * @param engine The engine which the post process will be applied. (default: current engine)
  77345. * @param reusable If the post process can be reused on the same frame. (default: false)
  77346. * @param textureType Type of textures used when performing the post process. (default: 0)
  77347. * @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)
  77348. */
  77349. function BlurPostProcess(name,
  77350. /** The direction in which to blur the image. */
  77351. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  77352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77353. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77354. if (defines === void 0) { defines = ""; }
  77355. if (blockCompilation === void 0) { blockCompilation = false; }
  77356. 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;
  77357. _this.direction = direction;
  77358. _this.blockCompilation = blockCompilation;
  77359. _this._packedFloat = false;
  77360. _this._staticDefines = "";
  77361. _this._staticDefines = defines;
  77362. _this.onApplyObservable.add(function (effect) {
  77363. if (_this._outputTexture) {
  77364. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  77365. }
  77366. else {
  77367. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  77368. }
  77369. });
  77370. _this.kernel = kernel;
  77371. return _this;
  77372. }
  77373. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  77374. /**
  77375. * Gets the length in pixels of the blur sample region
  77376. */
  77377. get: function () {
  77378. return this._idealKernel;
  77379. },
  77380. /**
  77381. * Sets the length in pixels of the blur sample region
  77382. */
  77383. set: function (v) {
  77384. if (this._idealKernel === v) {
  77385. return;
  77386. }
  77387. v = Math.max(v, 1);
  77388. this._idealKernel = v;
  77389. this._kernel = this._nearestBestKernel(v);
  77390. if (!this.blockCompilation) {
  77391. this._updateParameters();
  77392. }
  77393. },
  77394. enumerable: true,
  77395. configurable: true
  77396. });
  77397. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  77398. /**
  77399. * Gets wether or not the blur is unpacking/repacking floats
  77400. */
  77401. get: function () {
  77402. return this._packedFloat;
  77403. },
  77404. /**
  77405. * Sets wether or not the blur needs to unpack/repack floats
  77406. */
  77407. set: function (v) {
  77408. if (this._packedFloat === v) {
  77409. return;
  77410. }
  77411. this._packedFloat = v;
  77412. if (!this.blockCompilation) {
  77413. this._updateParameters();
  77414. }
  77415. },
  77416. enumerable: true,
  77417. configurable: true
  77418. });
  77419. /**
  77420. * Updates the effect with the current post process compile time values and recompiles the shader.
  77421. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77422. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77423. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77424. * @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
  77425. * @param onCompiled Called when the shader has been compiled.
  77426. * @param onError Called if there is an error when compiling a shader.
  77427. */
  77428. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77429. if (defines === void 0) { defines = null; }
  77430. if (uniforms === void 0) { uniforms = null; }
  77431. if (samplers === void 0) { samplers = null; }
  77432. this._updateParameters(onCompiled, onError);
  77433. };
  77434. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  77435. // Generate sampling offsets and weights
  77436. var N = this._kernel;
  77437. var centerIndex = (N - 1) / 2;
  77438. // Generate Gaussian sampling weights over kernel
  77439. var offsets = [];
  77440. var weights = [];
  77441. var totalWeight = 0;
  77442. for (var i = 0; i < N; i++) {
  77443. var u = i / (N - 1);
  77444. var w = this._gaussianWeight(u * 2.0 - 1);
  77445. offsets[i] = (i - centerIndex);
  77446. weights[i] = w;
  77447. totalWeight += w;
  77448. }
  77449. // Normalize weights
  77450. for (var i = 0; i < weights.length; i++) {
  77451. weights[i] /= totalWeight;
  77452. }
  77453. // Optimize: combine samples to take advantage of hardware linear sampling
  77454. // Walk from left to center, combining pairs (symmetrically)
  77455. var linearSamplingWeights = [];
  77456. var linearSamplingOffsets = [];
  77457. var linearSamplingMap = [];
  77458. for (var i = 0; i <= centerIndex; i += 2) {
  77459. var j = Math.min(i + 1, Math.floor(centerIndex));
  77460. var singleCenterSample = i === j;
  77461. if (singleCenterSample) {
  77462. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  77463. }
  77464. else {
  77465. var sharedCell = j === centerIndex;
  77466. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  77467. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  77468. if (offsetLinear === 0) {
  77469. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  77470. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  77471. }
  77472. else {
  77473. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  77474. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  77475. }
  77476. }
  77477. }
  77478. for (var i = 0; i < linearSamplingMap.length; i++) {
  77479. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  77480. linearSamplingWeights[i] = linearSamplingMap[i].w;
  77481. }
  77482. // Replace with optimized
  77483. offsets = linearSamplingOffsets;
  77484. weights = linearSamplingWeights;
  77485. // Generate shaders
  77486. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  77487. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  77488. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  77489. var defines = "";
  77490. defines += this._staticDefines;
  77491. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  77492. if (this._staticDefines.indexOf("DOF") != -1) {
  77493. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  77494. varyingCount--;
  77495. }
  77496. for (var i = 0; i < varyingCount; i++) {
  77497. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  77498. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  77499. }
  77500. var depCount = 0;
  77501. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  77502. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  77503. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  77504. depCount++;
  77505. }
  77506. if (this.packedFloat) {
  77507. defines += "#define PACKEDFLOAT 1";
  77508. }
  77509. this.blockCompilation = false;
  77510. _super.prototype.updateEffect.call(this, defines, null, null, {
  77511. varyingCount: varyingCount,
  77512. depCount: depCount
  77513. }, onCompiled, onError);
  77514. };
  77515. /**
  77516. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  77517. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  77518. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  77519. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  77520. * The gaps between physical kernels are compensated for in the weighting of the samples
  77521. * @param idealKernel Ideal blur kernel.
  77522. * @return Nearest best kernel.
  77523. */
  77524. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  77525. var v = Math.round(idealKernel);
  77526. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  77527. var k = _a[_i];
  77528. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  77529. return Math.max(k, 3);
  77530. }
  77531. }
  77532. return Math.max(v, 3);
  77533. };
  77534. /**
  77535. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  77536. * @param x The point on the Gaussian distribution to sample.
  77537. * @return the value of the Gaussian function at x.
  77538. */
  77539. BlurPostProcess.prototype._gaussianWeight = function (x) {
  77540. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  77541. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  77542. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  77543. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  77544. // truncated at around 1.3% of peak strength.
  77545. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  77546. var sigma = (1 / 3);
  77547. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  77548. var exponent = -((x * x) / (2.0 * sigma * sigma));
  77549. var weight = (1.0 / denominator) * Math.exp(exponent);
  77550. return weight;
  77551. };
  77552. /**
  77553. * Generates a string that can be used as a floating point number in GLSL.
  77554. * @param x Value to print.
  77555. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  77556. * @return GLSL float string.
  77557. */
  77558. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  77559. if (decimalFigures === void 0) { decimalFigures = 8; }
  77560. return x.toFixed(decimalFigures).replace(/0+$/, '');
  77561. };
  77562. return BlurPostProcess;
  77563. }(BABYLON.PostProcess));
  77564. BABYLON.BlurPostProcess = BlurPostProcess;
  77565. })(BABYLON || (BABYLON = {}));
  77566. //# sourceMappingURL=babylon.blurPostProcess.js.map
  77567. var BABYLON;
  77568. (function (BABYLON) {
  77569. /**
  77570. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  77571. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  77572. * based on samples that have a large difference in distance than the center pixel.
  77573. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77574. */
  77575. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  77576. __extends(DepthOfFieldBlurPostProcess, _super);
  77577. /**
  77578. * Creates a new instance CircleOfConfusionPostProcess
  77579. * @param name The name of the effect.
  77580. * @param scene The scene the effect belongs to.
  77581. * @param direction The direction the blur should be applied.
  77582. * @param kernel The size of the kernel used to blur.
  77583. * @param options The required width/height ratio to downsize to before computing the render pass.
  77584. * @param camera The camera to apply the render pass to.
  77585. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  77586. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  77587. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77588. * @param engine The engine which the post process will be applied. (default: current engine)
  77589. * @param reusable If the post process can be reused on the same frame. (default: false)
  77590. * @param textureType Type of textures used when performing the post process. (default: 0)
  77591. * @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)
  77592. */
  77593. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  77594. if (imageToBlur === void 0) { imageToBlur = null; }
  77595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77596. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77597. if (blockCompilation === void 0) { blockCompilation = false; }
  77598. 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;
  77599. _this.direction = direction;
  77600. _this.onApplyObservable.add(function (effect) {
  77601. if (imageToBlur != null) {
  77602. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  77603. }
  77604. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77605. if (scene.activeCamera) {
  77606. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77607. }
  77608. });
  77609. return _this;
  77610. }
  77611. return DepthOfFieldBlurPostProcess;
  77612. }(BABYLON.BlurPostProcess));
  77613. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  77614. })(BABYLON || (BABYLON = {}));
  77615. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  77616. var BABYLON;
  77617. (function (BABYLON) {
  77618. /**
  77619. * Options to be set when merging outputs from the default pipeline.
  77620. */
  77621. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  77622. function DepthOfFieldMergePostProcessOptions() {
  77623. }
  77624. return DepthOfFieldMergePostProcessOptions;
  77625. }());
  77626. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  77627. /**
  77628. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77629. */
  77630. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  77631. __extends(DepthOfFieldMergePostProcess, _super);
  77632. /**
  77633. * Creates a new instance of DepthOfFieldMergePostProcess
  77634. * @param name The name of the effect.
  77635. * @param originalFromInput Post process which's input will be used for the merge.
  77636. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  77637. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  77638. * @param options The required width/height ratio to downsize to before computing the render pass.
  77639. * @param camera The camera to apply the render pass to.
  77640. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77641. * @param engine The engine which the post process will be applied. (default: current engine)
  77642. * @param reusable If the post process can be reused on the same frame. (default: false)
  77643. * @param textureType Type of textures used when performing the post process. (default: 0)
  77644. * @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)
  77645. */
  77646. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77647. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77648. if (blockCompilation === void 0) { blockCompilation = false; }
  77649. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77650. _this.blurSteps = blurSteps;
  77651. _this.onApplyObservable.add(function (effect) {
  77652. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77653. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77654. blurSteps.forEach(function (step, index) {
  77655. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  77656. });
  77657. });
  77658. if (!blockCompilation) {
  77659. _this.updateEffect();
  77660. }
  77661. return _this;
  77662. }
  77663. /**
  77664. * Updates the effect with the current post process compile time values and recompiles the shader.
  77665. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77666. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77667. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77668. * @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
  77669. * @param onCompiled Called when the shader has been compiled.
  77670. * @param onError Called if there is an error when compiling a shader.
  77671. */
  77672. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77673. if (defines === void 0) { defines = null; }
  77674. if (uniforms === void 0) { uniforms = null; }
  77675. if (samplers === void 0) { samplers = null; }
  77676. if (!defines) {
  77677. defines = "";
  77678. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  77679. }
  77680. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  77681. };
  77682. return DepthOfFieldMergePostProcess;
  77683. }(BABYLON.PostProcess));
  77684. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  77685. })(BABYLON || (BABYLON = {}));
  77686. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  77687. var BABYLON;
  77688. (function (BABYLON) {
  77689. /**
  77690. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  77691. */
  77692. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  77693. __extends(CircleOfConfusionPostProcess, _super);
  77694. /**
  77695. * Creates a new instance CircleOfConfusionPostProcess
  77696. * @param name The name of the effect.
  77697. * @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.
  77698. * @param options The required width/height ratio to downsize to before computing the render pass.
  77699. * @param camera The camera to apply the render pass to.
  77700. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77701. * @param engine The engine which the post process will be applied. (default: current engine)
  77702. * @param reusable If the post process can be reused on the same frame. (default: false)
  77703. * @param textureType Type of textures used when performing the post process. (default: 0)
  77704. * @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)
  77705. */
  77706. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77707. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77708. if (blockCompilation === void 0) { blockCompilation = false; }
  77709. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77710. /**
  77711. * 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.
  77712. */
  77713. _this.lensSize = 50;
  77714. /**
  77715. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77716. */
  77717. _this.fStop = 1.4;
  77718. /**
  77719. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77720. */
  77721. _this.focusDistance = 2000;
  77722. /**
  77723. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  77724. */
  77725. _this.focalLength = 50;
  77726. _this._depthTexture = null;
  77727. _this._depthTexture = depthTexture;
  77728. _this.onApplyObservable.add(function (effect) {
  77729. if (!_this._depthTexture) {
  77730. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  77731. return;
  77732. }
  77733. effect.setTexture("depthSampler", _this._depthTexture);
  77734. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  77735. var aperture = _this.lensSize / _this.fStop;
  77736. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  77737. effect.setFloat('focusDistance', _this.focusDistance);
  77738. effect.setFloat('cocPrecalculation', cocPrecalculation);
  77739. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  77740. });
  77741. return _this;
  77742. }
  77743. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  77744. /**
  77745. * 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.
  77746. */
  77747. set: function (value) {
  77748. this._depthTexture = value;
  77749. },
  77750. enumerable: true,
  77751. configurable: true
  77752. });
  77753. return CircleOfConfusionPostProcess;
  77754. }(BABYLON.PostProcess));
  77755. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  77756. })(BABYLON || (BABYLON = {}));
  77757. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  77758. var BABYLON;
  77759. (function (BABYLON) {
  77760. /**
  77761. * Specifies the level of max blur that should be applied when using the depth of field effect
  77762. */
  77763. var DepthOfFieldEffectBlurLevel;
  77764. (function (DepthOfFieldEffectBlurLevel) {
  77765. /**
  77766. * Subtle blur
  77767. */
  77768. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  77769. /**
  77770. * Medium blur
  77771. */
  77772. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  77773. /**
  77774. * Large blur
  77775. */
  77776. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  77777. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  77778. ;
  77779. /**
  77780. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  77781. */
  77782. var DepthOfFieldEffect = /** @class */ (function (_super) {
  77783. __extends(DepthOfFieldEffect, _super);
  77784. /**
  77785. * Creates a new instance DepthOfFieldEffect
  77786. * @param scene The scene the effect belongs to.
  77787. * @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.
  77788. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77789. * @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)
  77790. */
  77791. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  77792. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  77793. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77794. if (blockCompilation === void 0) { blockCompilation = false; }
  77795. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  77796. return _this._effects;
  77797. }, true) || this;
  77798. /**
  77799. * Internal post processes in depth of field effect
  77800. */
  77801. _this._effects = [];
  77802. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  77803. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77804. // 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)
  77805. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  77806. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77807. _this._depthOfFieldBlurY = [];
  77808. _this._depthOfFieldBlurX = [];
  77809. var blurCount = 1;
  77810. var kernelSize = 15;
  77811. switch (blurLevel) {
  77812. case DepthOfFieldEffectBlurLevel.High: {
  77813. blurCount = 3;
  77814. kernelSize = 51;
  77815. break;
  77816. }
  77817. case DepthOfFieldEffectBlurLevel.Medium: {
  77818. blurCount = 2;
  77819. kernelSize = 31;
  77820. break;
  77821. }
  77822. default: {
  77823. kernelSize = 15;
  77824. blurCount = 1;
  77825. break;
  77826. }
  77827. }
  77828. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  77829. var ratio = 1.0;
  77830. for (var i = 0; i < blurCount; i++) {
  77831. 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);
  77832. blurY.autoClear = false;
  77833. ratio = 0.75 / Math.pow(2, i);
  77834. 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);
  77835. blurX.autoClear = false;
  77836. _this._depthOfFieldBlurY.push(blurY);
  77837. _this._depthOfFieldBlurX.push(blurX);
  77838. }
  77839. // Set all post processes on the effect.
  77840. _this._effects = [_this._circleOfConfusion];
  77841. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  77842. _this._effects.push(_this._depthOfFieldBlurY[i]);
  77843. _this._effects.push(_this._depthOfFieldBlurX[i]);
  77844. }
  77845. // Merge blurred images with original image based on circleOfConfusion
  77846. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77847. _this._dofMerge.autoClear = false;
  77848. _this._effects.push(_this._dofMerge);
  77849. return _this;
  77850. }
  77851. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  77852. get: function () {
  77853. return this._circleOfConfusion.focalLength;
  77854. },
  77855. /**
  77856. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  77857. */
  77858. set: function (value) {
  77859. this._circleOfConfusion.focalLength = value;
  77860. },
  77861. enumerable: true,
  77862. configurable: true
  77863. });
  77864. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  77865. get: function () {
  77866. return this._circleOfConfusion.fStop;
  77867. },
  77868. /**
  77869. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77870. */
  77871. set: function (value) {
  77872. this._circleOfConfusion.fStop = value;
  77873. },
  77874. enumerable: true,
  77875. configurable: true
  77876. });
  77877. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  77878. get: function () {
  77879. return this._circleOfConfusion.focusDistance;
  77880. },
  77881. /**
  77882. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77883. */
  77884. set: function (value) {
  77885. this._circleOfConfusion.focusDistance = value;
  77886. },
  77887. enumerable: true,
  77888. configurable: true
  77889. });
  77890. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  77891. get: function () {
  77892. return this._circleOfConfusion.lensSize;
  77893. },
  77894. /**
  77895. * 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.
  77896. */
  77897. set: function (value) {
  77898. this._circleOfConfusion.lensSize = value;
  77899. },
  77900. enumerable: true,
  77901. configurable: true
  77902. });
  77903. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  77904. /**
  77905. * 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.
  77906. */
  77907. set: function (value) {
  77908. this._circleOfConfusion.depthTexture = value;
  77909. },
  77910. enumerable: true,
  77911. configurable: true
  77912. });
  77913. /**
  77914. * Disposes each of the internal effects for a given camera.
  77915. * @param camera The camera to dispose the effect on.
  77916. */
  77917. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  77918. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77919. this._effects[effectIndex].dispose(camera);
  77920. }
  77921. };
  77922. /**
  77923. * Internal
  77924. */
  77925. DepthOfFieldEffect.prototype._updateEffects = function () {
  77926. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77927. this._effects[effectIndex].updateEffect();
  77928. }
  77929. };
  77930. /**
  77931. * Internal
  77932. * @returns if all the contained post processes are ready.
  77933. */
  77934. DepthOfFieldEffect.prototype._isReady = function () {
  77935. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77936. if (!this._effects[effectIndex].isReady()) {
  77937. return false;
  77938. }
  77939. }
  77940. return true;
  77941. };
  77942. return DepthOfFieldEffect;
  77943. }(BABYLON.PostProcessRenderEffect));
  77944. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  77945. })(BABYLON || (BABYLON = {}));
  77946. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  77947. var BABYLON;
  77948. (function (BABYLON) {
  77949. /**
  77950. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77951. */
  77952. var BloomMergePostProcess = /** @class */ (function (_super) {
  77953. __extends(BloomMergePostProcess, _super);
  77954. /**
  77955. * Creates a new instance of @see BloomMergePostProcess
  77956. * @param name The name of the effect.
  77957. * @param originalFromInput Post process which's input will be used for the merge.
  77958. * @param blurred Blurred highlights post process which's output will be used.
  77959. * @param weight Weight of the bloom to be added to the original input.
  77960. * @param options The required width/height ratio to downsize to before computing the render pass.
  77961. * @param camera The camera to apply the render pass to.
  77962. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77963. * @param engine The engine which the post process will be applied. (default: current engine)
  77964. * @param reusable If the post process can be reused on the same frame. (default: false)
  77965. * @param textureType Type of textures used when performing the post process. (default: 0)
  77966. * @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)
  77967. */
  77968. function BloomMergePostProcess(name, originalFromInput, blurred,
  77969. /** Weight of the bloom to be added to the original input. */
  77970. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77971. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77972. if (blockCompilation === void 0) { blockCompilation = false; }
  77973. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77974. _this.weight = weight;
  77975. _this.onApplyObservable.add(function (effect) {
  77976. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77977. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  77978. effect.setFloat("bloomWeight", _this.weight);
  77979. });
  77980. if (!blockCompilation) {
  77981. _this.updateEffect();
  77982. }
  77983. return _this;
  77984. }
  77985. return BloomMergePostProcess;
  77986. }(BABYLON.PostProcess));
  77987. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  77988. })(BABYLON || (BABYLON = {}));
  77989. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  77990. var BABYLON;
  77991. (function (BABYLON) {
  77992. /**
  77993. * 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.
  77994. */
  77995. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  77996. __extends(ExtractHighlightsPostProcess, _super);
  77997. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77998. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77999. if (blockCompilation === void 0) { blockCompilation = false; }
  78000. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78001. /**
  78002. * The luminance threshold, pixels below this value will be set to black.
  78003. */
  78004. _this.threshold = 0.9;
  78005. /**
  78006. * Internal
  78007. */
  78008. _this._exposure = 1;
  78009. /**
  78010. * Post process which has the input texture to be used when performing highlight extraction
  78011. */
  78012. _this._inputPostProcess = null;
  78013. _this.onApplyObservable.add(function (effect) {
  78014. if (_this._inputPostProcess) {
  78015. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  78016. }
  78017. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  78018. effect.setFloat('exposure', _this._exposure);
  78019. });
  78020. return _this;
  78021. }
  78022. return ExtractHighlightsPostProcess;
  78023. }(BABYLON.PostProcess));
  78024. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  78025. })(BABYLON || (BABYLON = {}));
  78026. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  78027. var BABYLON;
  78028. (function (BABYLON) {
  78029. /**
  78030. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  78031. */
  78032. var BloomEffect = /** @class */ (function (_super) {
  78033. __extends(BloomEffect, _super);
  78034. /**
  78035. * Creates a new instance of @see BloomEffect
  78036. * @param scene The scene the effect belongs to.
  78037. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  78038. * @param bloomKernel The size of the kernel to be used when applying the blur.
  78039. * @param bloomWeight The the strength of bloom.
  78040. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  78041. * @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)
  78042. */
  78043. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  78044. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  78045. if (blockCompilation === void 0) { blockCompilation = false; }
  78046. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  78047. return _this._effects;
  78048. }, true) || this;
  78049. _this.bloomScale = bloomScale;
  78050. /**
  78051. * Internal
  78052. */
  78053. _this._effects = [];
  78054. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78055. _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);
  78056. _this._blurX.alwaysForcePOT = true;
  78057. _this._blurX.autoClear = false;
  78058. _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);
  78059. _this._blurY.alwaysForcePOT = true;
  78060. _this._blurY.autoClear = false;
  78061. _this.kernel = bloomKernel;
  78062. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  78063. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78064. _this._merge.autoClear = false;
  78065. _this._effects.push(_this._merge);
  78066. return _this;
  78067. }
  78068. Object.defineProperty(BloomEffect.prototype, "threshold", {
  78069. /**
  78070. * The luminance threshold to find bright areas of the image to bloom.
  78071. */
  78072. get: function () {
  78073. return this._downscale.threshold;
  78074. },
  78075. set: function (value) {
  78076. this._downscale.threshold = value;
  78077. },
  78078. enumerable: true,
  78079. configurable: true
  78080. });
  78081. Object.defineProperty(BloomEffect.prototype, "weight", {
  78082. /**
  78083. * The strength of the bloom.
  78084. */
  78085. get: function () {
  78086. return this._merge.weight;
  78087. },
  78088. set: function (value) {
  78089. this._merge.weight = value;
  78090. },
  78091. enumerable: true,
  78092. configurable: true
  78093. });
  78094. Object.defineProperty(BloomEffect.prototype, "kernel", {
  78095. /**
  78096. * Specifies the size of the bloom blur kernel, relative to the final output size
  78097. */
  78098. get: function () {
  78099. return this._blurX.kernel / this.bloomScale;
  78100. },
  78101. set: function (value) {
  78102. this._blurX.kernel = value * this.bloomScale;
  78103. this._blurY.kernel = value * this.bloomScale;
  78104. },
  78105. enumerable: true,
  78106. configurable: true
  78107. });
  78108. /**
  78109. * Disposes each of the internal effects for a given camera.
  78110. * @param camera The camera to dispose the effect on.
  78111. */
  78112. BloomEffect.prototype.disposeEffects = function (camera) {
  78113. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78114. this._effects[effectIndex].dispose(camera);
  78115. }
  78116. };
  78117. /**
  78118. * Internal
  78119. */
  78120. BloomEffect.prototype._updateEffects = function () {
  78121. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78122. this._effects[effectIndex].updateEffect();
  78123. }
  78124. };
  78125. /**
  78126. * Internal
  78127. * @returns if all the contained post processes are ready.
  78128. */
  78129. BloomEffect.prototype._isReady = function () {
  78130. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78131. if (!this._effects[effectIndex].isReady()) {
  78132. return false;
  78133. }
  78134. }
  78135. return true;
  78136. };
  78137. return BloomEffect;
  78138. }(BABYLON.PostProcessRenderEffect));
  78139. BABYLON.BloomEffect = BloomEffect;
  78140. })(BABYLON || (BABYLON = {}));
  78141. //# sourceMappingURL=babylon.bloomEffect.js.map
  78142. var BABYLON;
  78143. (function (BABYLON) {
  78144. /**
  78145. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  78146. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  78147. */
  78148. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  78149. __extends(DefaultRenderingPipeline, _super);
  78150. /**
  78151. * @constructor
  78152. * @param {string} name - The rendering pipeline name (default: "")
  78153. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  78154. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  78155. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  78156. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  78157. */
  78158. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  78159. if (name === void 0) { name = ""; }
  78160. if (hdr === void 0) { hdr = true; }
  78161. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78162. if (automaticBuild === void 0) { automaticBuild = true; }
  78163. var _this = _super.call(this, scene.getEngine(), name) || this;
  78164. _this._camerasToBeAttached = [];
  78165. /**
  78166. * ID of the sharpen post process,
  78167. */
  78168. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  78169. /**
  78170. * ID of the image processing post process;
  78171. */
  78172. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  78173. /**
  78174. * ID of the Fast Approximate Anti-Aliasing post process;
  78175. */
  78176. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  78177. /**
  78178. * ID of the chromatic aberration post process,
  78179. */
  78180. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  78181. /**
  78182. * ID of the grain post process
  78183. */
  78184. _this.GrainPostProcessId = "GrainPostProcessEffect";
  78185. /**
  78186. * Glow post process which adds a glow to emmisive areas of the image
  78187. */
  78188. _this._glowLayer = null;
  78189. /**
  78190. * Animations which can be used to tweak settings over a period of time
  78191. */
  78192. _this.animations = [];
  78193. _this._imageProcessingConfigurationObserver = null;
  78194. // Values
  78195. _this._sharpenEnabled = false;
  78196. _this._bloomEnabled = false;
  78197. _this._depthOfFieldEnabled = false;
  78198. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  78199. _this._fxaaEnabled = false;
  78200. _this._imageProcessingEnabled = true;
  78201. _this._bloomScale = 0.5;
  78202. _this._chromaticAberrationEnabled = false;
  78203. _this._grainEnabled = false;
  78204. _this._buildAllowed = true;
  78205. _this._resizeObserver = null;
  78206. _this._hardwareScaleLevel = 1.0;
  78207. _this._bloomKernel = 64;
  78208. /**
  78209. * Specifies the weight of the bloom in the final rendering
  78210. */
  78211. _this._bloomWeight = 0.15;
  78212. /**
  78213. * Specifies the luma threshold for the area that will be blurred by the bloom
  78214. */
  78215. _this._bloomThreshold = 0.9;
  78216. _this._samples = 1;
  78217. _this._hasCleared = false;
  78218. _this._prevPostProcess = null;
  78219. _this._prevPrevPostProcess = null;
  78220. _this._cameras = cameras || scene.cameras;
  78221. _this._camerasToBeAttached = _this._cameras.slice();
  78222. _this._buildAllowed = automaticBuild;
  78223. // Initialize
  78224. _this._scene = scene;
  78225. var caps = _this._scene.getEngine().getCaps();
  78226. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  78227. // Misc
  78228. if (_this._hdr) {
  78229. if (caps.textureHalfFloatRender) {
  78230. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78231. }
  78232. else if (caps.textureFloatRender) {
  78233. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78234. }
  78235. }
  78236. else {
  78237. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78238. }
  78239. // Attach
  78240. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78241. var engine = _this._scene.getEngine();
  78242. // Create post processes before hand so they can be modified before enabled.
  78243. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  78244. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78245. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  78246. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  78247. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  78248. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78249. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  78250. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78251. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  78252. _this._resizeObserver = engine.onResizeObservable.add(function () {
  78253. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  78254. _this.bloomKernel = _this.bloomKernel;
  78255. });
  78256. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  78257. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  78258. });
  78259. _this._buildPipeline();
  78260. return _this;
  78261. }
  78262. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  78263. get: function () {
  78264. return this._sharpenEnabled;
  78265. },
  78266. /**
  78267. * Enable or disable the sharpen process from the pipeline
  78268. */
  78269. set: function (enabled) {
  78270. if (this._sharpenEnabled === enabled) {
  78271. return;
  78272. }
  78273. this._sharpenEnabled = enabled;
  78274. this._buildPipeline();
  78275. },
  78276. enumerable: true,
  78277. configurable: true
  78278. });
  78279. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  78280. /**
  78281. * Specifies the size of the bloom blur kernel, relative to the final output size
  78282. */
  78283. get: function () {
  78284. return this._bloomKernel;
  78285. },
  78286. set: function (value) {
  78287. this._bloomKernel = value;
  78288. this.bloom.kernel = value / this._hardwareScaleLevel;
  78289. },
  78290. enumerable: true,
  78291. configurable: true
  78292. });
  78293. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  78294. get: function () {
  78295. return this._bloomWeight;
  78296. },
  78297. /**
  78298. * The strength of the bloom.
  78299. */
  78300. set: function (value) {
  78301. if (this._bloomWeight === value) {
  78302. return;
  78303. }
  78304. this.bloom.weight = value;
  78305. this._bloomWeight = value;
  78306. },
  78307. enumerable: true,
  78308. configurable: true
  78309. });
  78310. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  78311. get: function () {
  78312. return this._bloomThreshold;
  78313. },
  78314. /**
  78315. * The strength of the bloom.
  78316. */
  78317. set: function (value) {
  78318. if (this._bloomThreshold === value) {
  78319. return;
  78320. }
  78321. this.bloom.threshold = value;
  78322. this._bloomThreshold = value;
  78323. },
  78324. enumerable: true,
  78325. configurable: true
  78326. });
  78327. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  78328. get: function () {
  78329. return this._bloomScale;
  78330. },
  78331. /**
  78332. * The scale of the bloom, lower value will provide better performance.
  78333. */
  78334. set: function (value) {
  78335. if (this._bloomScale === value) {
  78336. return;
  78337. }
  78338. this._bloomScale = value;
  78339. // recreate bloom and dispose old as this setting is not dynamic
  78340. this._rebuildBloom();
  78341. this._buildPipeline();
  78342. },
  78343. enumerable: true,
  78344. configurable: true
  78345. });
  78346. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  78347. get: function () {
  78348. return this._bloomEnabled;
  78349. },
  78350. /**
  78351. * Enable or disable the bloom from the pipeline
  78352. */
  78353. set: function (enabled) {
  78354. if (this._bloomEnabled === enabled) {
  78355. return;
  78356. }
  78357. this._bloomEnabled = enabled;
  78358. this._buildPipeline();
  78359. },
  78360. enumerable: true,
  78361. configurable: true
  78362. });
  78363. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  78364. // recreate bloom and dispose old as this setting is not dynamic
  78365. var oldBloom = this.bloom;
  78366. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  78367. this.bloom.threshold = oldBloom.threshold;
  78368. for (var i = 0; i < this._cameras.length; i++) {
  78369. oldBloom.disposeEffects(this._cameras[i]);
  78370. }
  78371. };
  78372. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  78373. /**
  78374. * If the depth of field is enabled.
  78375. */
  78376. get: function () {
  78377. return this._depthOfFieldEnabled;
  78378. },
  78379. set: function (enabled) {
  78380. if (this._depthOfFieldEnabled === enabled) {
  78381. return;
  78382. }
  78383. this._depthOfFieldEnabled = enabled;
  78384. this._buildPipeline();
  78385. },
  78386. enumerable: true,
  78387. configurable: true
  78388. });
  78389. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  78390. /**
  78391. * Blur level of the depth of field effect. (Higher blur will effect performance)
  78392. */
  78393. get: function () {
  78394. return this._depthOfFieldBlurLevel;
  78395. },
  78396. set: function (value) {
  78397. if (this._depthOfFieldBlurLevel === value) {
  78398. return;
  78399. }
  78400. this._depthOfFieldBlurLevel = value;
  78401. // recreate dof and dispose old as this setting is not dynamic
  78402. var oldDof = this.depthOfField;
  78403. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  78404. this.depthOfField.focalLength = oldDof.focalLength;
  78405. this.depthOfField.focusDistance = oldDof.focusDistance;
  78406. this.depthOfField.fStop = oldDof.fStop;
  78407. this.depthOfField.lensSize = oldDof.lensSize;
  78408. for (var i = 0; i < this._cameras.length; i++) {
  78409. oldDof.disposeEffects(this._cameras[i]);
  78410. }
  78411. this._buildPipeline();
  78412. },
  78413. enumerable: true,
  78414. configurable: true
  78415. });
  78416. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  78417. get: function () {
  78418. return this._fxaaEnabled;
  78419. },
  78420. /**
  78421. * If the anti aliasing is enabled.
  78422. */
  78423. set: function (enabled) {
  78424. if (this._fxaaEnabled === enabled) {
  78425. return;
  78426. }
  78427. this._fxaaEnabled = enabled;
  78428. this._buildPipeline();
  78429. },
  78430. enumerable: true,
  78431. configurable: true
  78432. });
  78433. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  78434. get: function () {
  78435. return this._samples;
  78436. },
  78437. /**
  78438. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  78439. */
  78440. set: function (sampleCount) {
  78441. if (this._samples === sampleCount) {
  78442. return;
  78443. }
  78444. this._samples = sampleCount;
  78445. this._buildPipeline();
  78446. },
  78447. enumerable: true,
  78448. configurable: true
  78449. });
  78450. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  78451. get: function () {
  78452. return this._imageProcessingEnabled;
  78453. },
  78454. /**
  78455. * If image processing is enabled.
  78456. */
  78457. set: function (enabled) {
  78458. if (this._imageProcessingEnabled === enabled) {
  78459. return;
  78460. }
  78461. this._imageProcessingEnabled = enabled;
  78462. this._buildPipeline();
  78463. },
  78464. enumerable: true,
  78465. configurable: true
  78466. });
  78467. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  78468. get: function () {
  78469. return this._glowLayer == null;
  78470. },
  78471. /**
  78472. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  78473. */
  78474. set: function (enabled) {
  78475. if (enabled && !this._glowLayer) {
  78476. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  78477. }
  78478. else if (!enabled && this._glowLayer) {
  78479. this._glowLayer.dispose();
  78480. this._glowLayer = null;
  78481. }
  78482. },
  78483. enumerable: true,
  78484. configurable: true
  78485. });
  78486. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  78487. get: function () {
  78488. return this._chromaticAberrationEnabled;
  78489. },
  78490. /**
  78491. * Enable or disable the chromaticAberration process from the pipeline
  78492. */
  78493. set: function (enabled) {
  78494. if (this._chromaticAberrationEnabled === enabled) {
  78495. return;
  78496. }
  78497. this._chromaticAberrationEnabled = enabled;
  78498. this._buildPipeline();
  78499. },
  78500. enumerable: true,
  78501. configurable: true
  78502. });
  78503. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  78504. get: function () {
  78505. return this._grainEnabled;
  78506. },
  78507. /**
  78508. * Enable or disable the grain process from the pipeline
  78509. */
  78510. set: function (enabled) {
  78511. if (this._grainEnabled === enabled) {
  78512. return;
  78513. }
  78514. this._grainEnabled = enabled;
  78515. this._buildPipeline();
  78516. },
  78517. enumerable: true,
  78518. configurable: true
  78519. });
  78520. /**
  78521. * Force the compilation of the entire pipeline.
  78522. */
  78523. DefaultRenderingPipeline.prototype.prepare = function () {
  78524. var previousState = this._buildAllowed;
  78525. this._buildAllowed = true;
  78526. this._buildPipeline();
  78527. this._buildAllowed = previousState;
  78528. };
  78529. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  78530. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  78531. if (this._hasCleared) {
  78532. postProcess.autoClear = false;
  78533. }
  78534. else {
  78535. postProcess.autoClear = true;
  78536. this._scene.autoClear = false;
  78537. this._hasCleared = true;
  78538. }
  78539. if (!skipTextureSharing) {
  78540. if (this._prevPrevPostProcess) {
  78541. postProcess.shareOutputWith(this._prevPrevPostProcess);
  78542. }
  78543. else {
  78544. postProcess.useOwnOutput();
  78545. }
  78546. if (this._prevPostProcess) {
  78547. this._prevPrevPostProcess = this._prevPostProcess;
  78548. }
  78549. this._prevPostProcess = postProcess;
  78550. }
  78551. };
  78552. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  78553. var _this = this;
  78554. if (!this._buildAllowed) {
  78555. return;
  78556. }
  78557. this._scene.autoClear = true;
  78558. var engine = this._scene.getEngine();
  78559. this._disposePostProcesses();
  78560. if (this._cameras !== null) {
  78561. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78562. // get back cameras to be used to reattach pipeline
  78563. this._cameras = this._camerasToBeAttached.slice();
  78564. }
  78565. this._reset();
  78566. this._prevPostProcess = null;
  78567. this._prevPrevPostProcess = null;
  78568. this._hasCleared = false;
  78569. if (this.depthOfFieldEnabled) {
  78570. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  78571. this.depthOfField.depthTexture = depthTexture;
  78572. if (!this.depthOfField._isReady()) {
  78573. this.depthOfField._updateEffects();
  78574. }
  78575. this.addEffect(this.depthOfField);
  78576. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  78577. }
  78578. if (this.bloomEnabled) {
  78579. if (!this.bloom._isReady()) {
  78580. this.bloom._updateEffects();
  78581. }
  78582. this.addEffect(this.bloom);
  78583. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  78584. }
  78585. if (this._imageProcessingEnabled) {
  78586. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78587. if (this._hdr) {
  78588. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  78589. this._setAutoClearAndTextureSharing(this.imageProcessing);
  78590. }
  78591. else {
  78592. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  78593. }
  78594. }
  78595. if (this.sharpenEnabled) {
  78596. if (!this.sharpen.isReady()) {
  78597. this.sharpen.updateEffect();
  78598. }
  78599. this.addEffect(this._sharpenEffect);
  78600. this._setAutoClearAndTextureSharing(this.sharpen);
  78601. }
  78602. if (this.grainEnabled) {
  78603. if (!this.grain.isReady()) {
  78604. this.grain.updateEffect();
  78605. }
  78606. this.addEffect(this._grainEffect);
  78607. this._setAutoClearAndTextureSharing(this.grain);
  78608. }
  78609. if (this.chromaticAberrationEnabled) {
  78610. if (!this.chromaticAberration.isReady()) {
  78611. this.chromaticAberration.updateEffect();
  78612. }
  78613. this.addEffect(this._chromaticAberrationEffect);
  78614. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  78615. }
  78616. if (this.fxaaEnabled) {
  78617. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78618. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  78619. this._setAutoClearAndTextureSharing(this.fxaa, true);
  78620. }
  78621. if (this._cameras !== null) {
  78622. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78623. }
  78624. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  78625. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78626. }
  78627. };
  78628. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  78629. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  78630. for (var i = 0; i < this._cameras.length; i++) {
  78631. var camera = this._cameras[i];
  78632. if (this.imageProcessing) {
  78633. this.imageProcessing.dispose(camera);
  78634. }
  78635. if (this.fxaa) {
  78636. this.fxaa.dispose(camera);
  78637. }
  78638. // These are created in the constructor and should not be disposed on every pipeline change
  78639. if (disposeNonRecreated) {
  78640. if (this.sharpen) {
  78641. this.sharpen.dispose(camera);
  78642. }
  78643. if (this.depthOfField) {
  78644. this.depthOfField.disposeEffects(camera);
  78645. }
  78646. if (this.bloom) {
  78647. this.bloom.disposeEffects(camera);
  78648. }
  78649. if (this.chromaticAberration) {
  78650. this.chromaticAberration.dispose(camera);
  78651. }
  78652. if (this.grain) {
  78653. this.grain.dispose(camera);
  78654. }
  78655. if (this._glowLayer) {
  78656. this._glowLayer.dispose();
  78657. }
  78658. }
  78659. }
  78660. this.imageProcessing = null;
  78661. this.fxaa = null;
  78662. if (disposeNonRecreated) {
  78663. this.sharpen = null;
  78664. this._sharpenEffect = null;
  78665. this.depthOfField = null;
  78666. this.bloom = null;
  78667. this.chromaticAberration = null;
  78668. this._chromaticAberrationEffect = null;
  78669. this.grain = null;
  78670. this._grainEffect = null;
  78671. this._glowLayer = null;
  78672. }
  78673. };
  78674. /**
  78675. * Adds a camera to the pipeline
  78676. * @param camera the camera to be added
  78677. */
  78678. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  78679. this._camerasToBeAttached.push(camera);
  78680. this._buildPipeline();
  78681. };
  78682. /**
  78683. * Removes a camera from the pipeline
  78684. * @param camera the camera to remove
  78685. */
  78686. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  78687. var index = this._camerasToBeAttached.indexOf(camera);
  78688. this._camerasToBeAttached.splice(index, 1);
  78689. this._buildPipeline();
  78690. };
  78691. /**
  78692. * Dispose of the pipeline and stop all post processes
  78693. */
  78694. DefaultRenderingPipeline.prototype.dispose = function () {
  78695. this._disposePostProcesses(true);
  78696. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78697. this._scene.autoClear = true;
  78698. if (this._resizeObserver) {
  78699. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  78700. this._resizeObserver = null;
  78701. }
  78702. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  78703. _super.prototype.dispose.call(this);
  78704. };
  78705. /**
  78706. * Serialize the rendering pipeline (Used when exporting)
  78707. * @returns the serialized object
  78708. */
  78709. DefaultRenderingPipeline.prototype.serialize = function () {
  78710. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78711. serializationObject.customType = "DefaultRenderingPipeline";
  78712. return serializationObject;
  78713. };
  78714. /**
  78715. * Parse the serialized pipeline
  78716. * @param source Source pipeline.
  78717. * @param scene The scene to load the pipeline to.
  78718. * @param rootUrl The URL of the serialized pipeline.
  78719. * @returns An instantiated pipeline from the serialized object.
  78720. */
  78721. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78722. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  78723. };
  78724. __decorate([
  78725. BABYLON.serialize()
  78726. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  78727. __decorate([
  78728. BABYLON.serialize()
  78729. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  78730. __decorate([
  78731. BABYLON.serialize()
  78732. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  78733. __decorate([
  78734. BABYLON.serialize()
  78735. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  78736. __decorate([
  78737. BABYLON.serialize()
  78738. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  78739. __decorate([
  78740. BABYLON.serialize()
  78741. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  78742. __decorate([
  78743. BABYLON.serialize()
  78744. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  78745. __decorate([
  78746. BABYLON.serialize()
  78747. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  78748. __decorate([
  78749. BABYLON.serialize()
  78750. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  78751. __decorate([
  78752. BABYLON.serialize()
  78753. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  78754. __decorate([
  78755. BABYLON.serialize()
  78756. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  78757. __decorate([
  78758. BABYLON.serialize()
  78759. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  78760. __decorate([
  78761. BABYLON.serialize()
  78762. ], DefaultRenderingPipeline.prototype, "samples", null);
  78763. __decorate([
  78764. BABYLON.serialize()
  78765. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  78766. __decorate([
  78767. BABYLON.serialize()
  78768. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  78769. __decorate([
  78770. BABYLON.serialize()
  78771. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  78772. __decorate([
  78773. BABYLON.serialize()
  78774. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  78775. return DefaultRenderingPipeline;
  78776. }(BABYLON.PostProcessRenderPipeline));
  78777. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  78778. })(BABYLON || (BABYLON = {}));
  78779. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  78780. var BABYLON;
  78781. (function (BABYLON) {
  78782. /**
  78783. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78784. */
  78785. var GeometryBufferRenderer = /** @class */ (function () {
  78786. /**
  78787. * Creates a new G Buffer for the scene
  78788. * @param scene The scene the buffer belongs to
  78789. * @param ratio How big is the buffer related to the main canvas.
  78790. */
  78791. function GeometryBufferRenderer(scene, ratio) {
  78792. if (ratio === void 0) { ratio = 1; }
  78793. this._enablePosition = false;
  78794. this._scene = scene;
  78795. this._ratio = ratio;
  78796. // Render target
  78797. this._createRenderTargets();
  78798. }
  78799. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78800. /**
  78801. * Set the render list (meshes to be rendered) used in the G buffer.
  78802. */
  78803. set: function (meshes) {
  78804. this._multiRenderTarget.renderList = meshes;
  78805. },
  78806. enumerable: true,
  78807. configurable: true
  78808. });
  78809. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78810. /**
  78811. * Gets wether or not G buffer are supported by the running hardware.
  78812. * This requires draw buffer supports
  78813. */
  78814. get: function () {
  78815. return this._multiRenderTarget.isSupported;
  78816. },
  78817. enumerable: true,
  78818. configurable: true
  78819. });
  78820. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78821. /**
  78822. * Gets wether or not position are enabled for the G buffer.
  78823. */
  78824. get: function () {
  78825. return this._enablePosition;
  78826. },
  78827. /**
  78828. * Sets wether or not position are enabled for the G buffer.
  78829. */
  78830. set: function (enable) {
  78831. this._enablePosition = enable;
  78832. this.dispose();
  78833. this._createRenderTargets();
  78834. },
  78835. enumerable: true,
  78836. configurable: true
  78837. });
  78838. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78839. /**
  78840. * Gets the scene associated with the buffer.
  78841. */
  78842. get: function () {
  78843. return this._scene;
  78844. },
  78845. enumerable: true,
  78846. configurable: true
  78847. });
  78848. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78849. /**
  78850. * Gets the ratio used by the buffer during its creation.
  78851. * How big is the buffer related to the main canvas.
  78852. */
  78853. get: function () {
  78854. return this._ratio;
  78855. },
  78856. enumerable: true,
  78857. configurable: true
  78858. });
  78859. /**
  78860. * Checks wether everything is ready to render a submesh to the G buffer.
  78861. * @param subMesh the submesh to check readiness for
  78862. * @param useInstances is the mesh drawn using instance or not
  78863. * @returns true if ready otherwise false
  78864. */
  78865. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78866. var material = subMesh.getMaterial();
  78867. if (material && material.disableDepthWrite) {
  78868. return false;
  78869. }
  78870. var defines = [];
  78871. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78872. var mesh = subMesh.getMesh();
  78873. // Alpha test
  78874. if (material && material.needAlphaTesting()) {
  78875. defines.push("#define ALPHATEST");
  78876. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78877. attribs.push(BABYLON.VertexBuffer.UVKind);
  78878. defines.push("#define UV1");
  78879. }
  78880. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78881. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78882. defines.push("#define UV2");
  78883. }
  78884. }
  78885. // Buffers
  78886. if (this._enablePosition) {
  78887. defines.push("#define POSITION");
  78888. }
  78889. // Bones
  78890. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78891. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78892. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78893. if (mesh.numBoneInfluencers > 4) {
  78894. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78895. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78896. }
  78897. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78898. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78899. }
  78900. else {
  78901. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78902. }
  78903. // Instances
  78904. if (useInstances) {
  78905. defines.push("#define INSTANCES");
  78906. attribs.push("world0");
  78907. attribs.push("world1");
  78908. attribs.push("world2");
  78909. attribs.push("world3");
  78910. }
  78911. // Get correct effect
  78912. var join = defines.join("\n");
  78913. if (this._cachedDefines !== join) {
  78914. this._cachedDefines = join;
  78915. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78916. }
  78917. return this._effect.isReady();
  78918. };
  78919. /**
  78920. * Gets the current underlying G Buffer.
  78921. * @returns the buffer
  78922. */
  78923. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78924. return this._multiRenderTarget;
  78925. };
  78926. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78927. /**
  78928. * Gets the number of samples used to render the buffer (anti aliasing).
  78929. */
  78930. get: function () {
  78931. return this._multiRenderTarget.samples;
  78932. },
  78933. /**
  78934. * Sets the number of samples used to render the buffer (anti aliasing).
  78935. */
  78936. set: function (value) {
  78937. this._multiRenderTarget.samples = value;
  78938. },
  78939. enumerable: true,
  78940. configurable: true
  78941. });
  78942. /**
  78943. * Disposes the renderer and frees up associated resources.
  78944. */
  78945. GeometryBufferRenderer.prototype.dispose = function () {
  78946. this.getGBuffer().dispose();
  78947. };
  78948. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78949. var _this = this;
  78950. var engine = this._scene.getEngine();
  78951. var count = this._enablePosition ? 3 : 2;
  78952. 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 });
  78953. if (!this.isSupported) {
  78954. return;
  78955. }
  78956. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78957. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78958. this._multiRenderTarget.refreshRate = 1;
  78959. this._multiRenderTarget.renderParticles = false;
  78960. this._multiRenderTarget.renderList = null;
  78961. // set default depth value to 1.0 (far away)
  78962. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78963. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78964. });
  78965. // Custom render function
  78966. var renderSubMesh = function (subMesh) {
  78967. var mesh = subMesh.getRenderingMesh();
  78968. var scene = _this._scene;
  78969. var engine = scene.getEngine();
  78970. var material = subMesh.getMaterial();
  78971. if (!material) {
  78972. return;
  78973. }
  78974. // Culling
  78975. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78976. // Managing instances
  78977. var batch = mesh._getInstancesRenderList(subMesh._id);
  78978. if (batch.mustReturn) {
  78979. return;
  78980. }
  78981. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78982. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78983. engine.enableEffect(_this._effect);
  78984. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78985. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78986. _this._effect.setMatrix("view", scene.getViewMatrix());
  78987. // Alpha test
  78988. if (material && material.needAlphaTesting()) {
  78989. var alphaTexture = material.getAlphaTestTexture();
  78990. if (alphaTexture) {
  78991. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78992. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78993. }
  78994. }
  78995. // Bones
  78996. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78997. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78998. }
  78999. // Draw
  79000. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79001. }
  79002. };
  79003. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79004. var index;
  79005. if (depthOnlySubMeshes.length) {
  79006. engine.setColorWrite(false);
  79007. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79008. renderSubMesh(depthOnlySubMeshes.data[index]);
  79009. }
  79010. engine.setColorWrite(true);
  79011. }
  79012. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79013. renderSubMesh(opaqueSubMeshes.data[index]);
  79014. }
  79015. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79016. renderSubMesh(alphaTestSubMeshes.data[index]);
  79017. }
  79018. };
  79019. };
  79020. return GeometryBufferRenderer;
  79021. }());
  79022. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  79023. })(BABYLON || (BABYLON = {}));
  79024. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  79025. var BABYLON;
  79026. (function (BABYLON) {
  79027. /**
  79028. * This groups together the common properties used for image processing either in direct forward pass
  79029. * or through post processing effect depending on the use of the image processing pipeline in your scene
  79030. * or not.
  79031. */
  79032. var ImageProcessingConfiguration = /** @class */ (function () {
  79033. function ImageProcessingConfiguration() {
  79034. /**
  79035. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  79036. */
  79037. this.colorCurves = new BABYLON.ColorCurves();
  79038. this._colorCurvesEnabled = false;
  79039. this._colorGradingEnabled = false;
  79040. this._colorGradingWithGreenDepth = true;
  79041. this._colorGradingBGR = true;
  79042. this._exposure = 1.0;
  79043. this._toneMappingEnabled = false;
  79044. this._contrast = 1.0;
  79045. /**
  79046. * Vignette stretch size.
  79047. */
  79048. this.vignetteStretch = 0;
  79049. /**
  79050. * Vignette centre X Offset.
  79051. */
  79052. this.vignetteCentreX = 0;
  79053. /**
  79054. * Vignette centre Y Offset.
  79055. */
  79056. this.vignetteCentreY = 0;
  79057. /**
  79058. * Vignette weight or intensity of the vignette effect.
  79059. */
  79060. this.vignetteWeight = 1.5;
  79061. /**
  79062. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79063. * if vignetteEnabled is set to true.
  79064. */
  79065. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79066. /**
  79067. * Camera field of view used by the Vignette effect.
  79068. */
  79069. this.vignetteCameraFov = 0.5;
  79070. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  79071. this._vignetteEnabled = false;
  79072. this._applyByPostProcess = false;
  79073. this._isEnabled = true;
  79074. /**
  79075. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  79076. */
  79077. this.onUpdateParameters = new BABYLON.Observable();
  79078. }
  79079. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  79080. /**
  79081. * Gets wether the color curves effect is enabled.
  79082. */
  79083. get: function () {
  79084. return this._colorCurvesEnabled;
  79085. },
  79086. /**
  79087. * Sets wether the color curves effect is enabled.
  79088. */
  79089. set: function (value) {
  79090. if (this._colorCurvesEnabled === value) {
  79091. return;
  79092. }
  79093. this._colorCurvesEnabled = value;
  79094. this._updateParameters();
  79095. },
  79096. enumerable: true,
  79097. configurable: true
  79098. });
  79099. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  79100. /**
  79101. * Gets wether the color grading effect is enabled.
  79102. */
  79103. get: function () {
  79104. return this._colorGradingEnabled;
  79105. },
  79106. /**
  79107. * Sets wether the color grading effect is enabled.
  79108. */
  79109. set: function (value) {
  79110. if (this._colorGradingEnabled === value) {
  79111. return;
  79112. }
  79113. this._colorGradingEnabled = value;
  79114. this._updateParameters();
  79115. },
  79116. enumerable: true,
  79117. configurable: true
  79118. });
  79119. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  79120. /**
  79121. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  79122. */
  79123. get: function () {
  79124. return this._colorGradingWithGreenDepth;
  79125. },
  79126. /**
  79127. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  79128. */
  79129. set: function (value) {
  79130. if (this._colorGradingWithGreenDepth === value) {
  79131. return;
  79132. }
  79133. this._colorGradingWithGreenDepth = value;
  79134. this._updateParameters();
  79135. },
  79136. enumerable: true,
  79137. configurable: true
  79138. });
  79139. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  79140. /**
  79141. * Gets wether the color grading texture contains BGR values.
  79142. */
  79143. get: function () {
  79144. return this._colorGradingBGR;
  79145. },
  79146. /**
  79147. * Sets wether the color grading texture contains BGR values.
  79148. */
  79149. set: function (value) {
  79150. if (this._colorGradingBGR === value) {
  79151. return;
  79152. }
  79153. this._colorGradingBGR = value;
  79154. this._updateParameters();
  79155. },
  79156. enumerable: true,
  79157. configurable: true
  79158. });
  79159. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  79160. /**
  79161. * Gets the Exposure used in the effect.
  79162. */
  79163. get: function () {
  79164. return this._exposure;
  79165. },
  79166. /**
  79167. * Sets the Exposure used in the effect.
  79168. */
  79169. set: function (value) {
  79170. if (this._exposure === value) {
  79171. return;
  79172. }
  79173. this._exposure = value;
  79174. this._updateParameters();
  79175. },
  79176. enumerable: true,
  79177. configurable: true
  79178. });
  79179. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  79180. /**
  79181. * Gets wether the tone mapping effect is enabled.
  79182. */
  79183. get: function () {
  79184. return this._toneMappingEnabled;
  79185. },
  79186. /**
  79187. * Sets wether the tone mapping effect is enabled.
  79188. */
  79189. set: function (value) {
  79190. if (this._toneMappingEnabled === value) {
  79191. return;
  79192. }
  79193. this._toneMappingEnabled = value;
  79194. this._updateParameters();
  79195. },
  79196. enumerable: true,
  79197. configurable: true
  79198. });
  79199. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  79200. /**
  79201. * Gets the contrast used in the effect.
  79202. */
  79203. get: function () {
  79204. return this._contrast;
  79205. },
  79206. /**
  79207. * Sets the contrast used in the effect.
  79208. */
  79209. set: function (value) {
  79210. if (this._contrast === value) {
  79211. return;
  79212. }
  79213. this._contrast = value;
  79214. this._updateParameters();
  79215. },
  79216. enumerable: true,
  79217. configurable: true
  79218. });
  79219. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  79220. /**
  79221. * Gets the vignette blend mode allowing different kind of effect.
  79222. */
  79223. get: function () {
  79224. return this._vignetteBlendMode;
  79225. },
  79226. /**
  79227. * Sets the vignette blend mode allowing different kind of effect.
  79228. */
  79229. set: function (value) {
  79230. if (this._vignetteBlendMode === value) {
  79231. return;
  79232. }
  79233. this._vignetteBlendMode = value;
  79234. this._updateParameters();
  79235. },
  79236. enumerable: true,
  79237. configurable: true
  79238. });
  79239. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  79240. /**
  79241. * Gets wether the vignette effect is enabled.
  79242. */
  79243. get: function () {
  79244. return this._vignetteEnabled;
  79245. },
  79246. /**
  79247. * Sets wether the vignette effect is enabled.
  79248. */
  79249. set: function (value) {
  79250. if (this._vignetteEnabled === value) {
  79251. return;
  79252. }
  79253. this._vignetteEnabled = value;
  79254. this._updateParameters();
  79255. },
  79256. enumerable: true,
  79257. configurable: true
  79258. });
  79259. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  79260. /**
  79261. * Gets wether the image processing is applied through a post process or not.
  79262. */
  79263. get: function () {
  79264. return this._applyByPostProcess;
  79265. },
  79266. /**
  79267. * Sets wether the image processing is applied through a post process or not.
  79268. */
  79269. set: function (value) {
  79270. if (this._applyByPostProcess === value) {
  79271. return;
  79272. }
  79273. this._applyByPostProcess = value;
  79274. this._updateParameters();
  79275. },
  79276. enumerable: true,
  79277. configurable: true
  79278. });
  79279. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  79280. /**
  79281. * Gets wether the image processing is enabled or not.
  79282. */
  79283. get: function () {
  79284. return this._isEnabled;
  79285. },
  79286. /**
  79287. * Sets wether the image processing is enabled or not.
  79288. */
  79289. set: function (value) {
  79290. if (this._isEnabled === value) {
  79291. return;
  79292. }
  79293. this._isEnabled = value;
  79294. this._updateParameters();
  79295. },
  79296. enumerable: true,
  79297. configurable: true
  79298. });
  79299. /**
  79300. * Method called each time the image processing information changes requires to recompile the effect.
  79301. */
  79302. ImageProcessingConfiguration.prototype._updateParameters = function () {
  79303. this.onUpdateParameters.notifyObservers(this);
  79304. };
  79305. ImageProcessingConfiguration.prototype.getClassName = function () {
  79306. return "ImageProcessingConfiguration";
  79307. };
  79308. /**
  79309. * Prepare the list of uniforms associated with the Image Processing effects.
  79310. * @param uniformsList The list of uniforms used in the effect
  79311. * @param defines the list of defines currently in use
  79312. */
  79313. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  79314. if (defines.EXPOSURE) {
  79315. uniforms.push("exposureLinear");
  79316. }
  79317. if (defines.CONTRAST) {
  79318. uniforms.push("contrast");
  79319. }
  79320. if (defines.COLORGRADING) {
  79321. uniforms.push("colorTransformSettings");
  79322. }
  79323. if (defines.VIGNETTE) {
  79324. uniforms.push("vInverseScreenSize");
  79325. uniforms.push("vignetteSettings1");
  79326. uniforms.push("vignetteSettings2");
  79327. }
  79328. if (defines.COLORCURVES) {
  79329. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  79330. }
  79331. };
  79332. /**
  79333. * Prepare the list of samplers associated with the Image Processing effects.
  79334. * @param uniformsList The list of uniforms used in the effect
  79335. * @param defines the list of defines currently in use
  79336. */
  79337. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  79338. if (defines.COLORGRADING) {
  79339. samplersList.push("txColorTransform");
  79340. }
  79341. };
  79342. /**
  79343. * Prepare the list of defines associated to the shader.
  79344. * @param defines the list of defines to complete
  79345. */
  79346. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  79347. if (forPostProcess === void 0) { forPostProcess = false; }
  79348. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  79349. defines.VIGNETTE = false;
  79350. defines.TONEMAPPING = false;
  79351. defines.CONTRAST = false;
  79352. defines.EXPOSURE = false;
  79353. defines.COLORCURVES = false;
  79354. defines.COLORGRADING = false;
  79355. defines.COLORGRADING3D = false;
  79356. defines.IMAGEPROCESSING = false;
  79357. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  79358. return;
  79359. }
  79360. defines.VIGNETTE = this.vignetteEnabled;
  79361. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  79362. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  79363. defines.TONEMAPPING = this.toneMappingEnabled;
  79364. defines.CONTRAST = (this.contrast !== 1.0);
  79365. defines.EXPOSURE = (this.exposure !== 1.0);
  79366. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  79367. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  79368. if (defines.COLORGRADING) {
  79369. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  79370. }
  79371. else {
  79372. defines.COLORGRADING3D = false;
  79373. }
  79374. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  79375. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  79376. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  79377. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  79378. };
  79379. /**
  79380. * Returns true if all the image processing information are ready.
  79381. */
  79382. ImageProcessingConfiguration.prototype.isReady = function () {
  79383. // Color Grading texure can not be none blocking.
  79384. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  79385. };
  79386. /**
  79387. * Binds the image processing to the shader.
  79388. * @param effect The effect to bind to
  79389. */
  79390. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  79391. if (aspectRatio === void 0) { aspectRatio = 1; }
  79392. // Color Curves
  79393. if (this._colorCurvesEnabled && this.colorCurves) {
  79394. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  79395. }
  79396. // Vignette
  79397. if (this._vignetteEnabled) {
  79398. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  79399. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  79400. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  79401. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  79402. var vignetteScaleX = vignetteScaleY * aspectRatio;
  79403. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  79404. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  79405. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  79406. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  79407. var vignettePower = -2.0 * this.vignetteWeight;
  79408. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  79409. }
  79410. // Exposure
  79411. effect.setFloat("exposureLinear", this.exposure);
  79412. // Contrast
  79413. effect.setFloat("contrast", this.contrast);
  79414. // Color transform settings
  79415. if (this.colorGradingTexture) {
  79416. effect.setTexture("txColorTransform", this.colorGradingTexture);
  79417. var textureSize = this.colorGradingTexture.getSize().height;
  79418. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  79419. 0.5 / textureSize, // textureOffset
  79420. textureSize, // textureSize
  79421. this.colorGradingTexture.level // weight
  79422. );
  79423. }
  79424. };
  79425. /**
  79426. * Clones the current image processing instance.
  79427. * @return The cloned image processing
  79428. */
  79429. ImageProcessingConfiguration.prototype.clone = function () {
  79430. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  79431. };
  79432. /**
  79433. * Serializes the current image processing instance to a json representation.
  79434. * @return a JSON representation
  79435. */
  79436. ImageProcessingConfiguration.prototype.serialize = function () {
  79437. return BABYLON.SerializationHelper.Serialize(this);
  79438. };
  79439. /**
  79440. * Parses the image processing from a json representation.
  79441. * @param source the JSON source to parse
  79442. * @return The parsed image processing
  79443. */
  79444. ImageProcessingConfiguration.Parse = function (source) {
  79445. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  79446. };
  79447. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  79448. /**
  79449. * Used to apply the vignette as a mix with the pixel color.
  79450. */
  79451. get: function () {
  79452. return this._VIGNETTEMODE_MULTIPLY;
  79453. },
  79454. enumerable: true,
  79455. configurable: true
  79456. });
  79457. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  79458. /**
  79459. * Used to apply the vignette as a replacement of the pixel color.
  79460. */
  79461. get: function () {
  79462. return this._VIGNETTEMODE_OPAQUE;
  79463. },
  79464. enumerable: true,
  79465. configurable: true
  79466. });
  79467. // Static constants associated to the image processing.
  79468. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  79469. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  79470. __decorate([
  79471. BABYLON.serializeAsColorCurves()
  79472. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  79473. __decorate([
  79474. BABYLON.serialize()
  79475. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  79476. __decorate([
  79477. BABYLON.serializeAsTexture()
  79478. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  79479. __decorate([
  79480. BABYLON.serialize()
  79481. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  79482. __decorate([
  79483. BABYLON.serialize()
  79484. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  79485. __decorate([
  79486. BABYLON.serialize()
  79487. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  79488. __decorate([
  79489. BABYLON.serialize()
  79490. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  79491. __decorate([
  79492. BABYLON.serialize()
  79493. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  79494. __decorate([
  79495. BABYLON.serialize()
  79496. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  79497. __decorate([
  79498. BABYLON.serialize()
  79499. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  79500. __decorate([
  79501. BABYLON.serialize()
  79502. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  79503. __decorate([
  79504. BABYLON.serialize()
  79505. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  79506. __decorate([
  79507. BABYLON.serialize()
  79508. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  79509. __decorate([
  79510. BABYLON.serializeAsColor4()
  79511. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  79512. __decorate([
  79513. BABYLON.serialize()
  79514. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  79515. __decorate([
  79516. BABYLON.serialize()
  79517. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  79518. __decorate([
  79519. BABYLON.serialize()
  79520. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  79521. __decorate([
  79522. BABYLON.serialize()
  79523. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  79524. __decorate([
  79525. BABYLON.serialize()
  79526. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  79527. return ImageProcessingConfiguration;
  79528. }());
  79529. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  79530. })(BABYLON || (BABYLON = {}));
  79531. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  79532. var BABYLON;
  79533. (function (BABYLON) {
  79534. /**
  79535. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  79536. * It can help converting any input color in a desired output one. This can then be used to create effects
  79537. * from sepia, black and white to sixties or futuristic rendering...
  79538. *
  79539. * The only supported format is currently 3dl.
  79540. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  79541. */
  79542. var ColorGradingTexture = /** @class */ (function (_super) {
  79543. __extends(ColorGradingTexture, _super);
  79544. /**
  79545. * Instantiates a ColorGradingTexture from the following parameters.
  79546. *
  79547. * @param url The location of the color gradind data (currently only supporting 3dl)
  79548. * @param scene The scene the texture will be used in
  79549. */
  79550. function ColorGradingTexture(url, scene) {
  79551. var _this = _super.call(this, scene) || this;
  79552. if (!url) {
  79553. return _this;
  79554. }
  79555. _this._engine = scene.getEngine();
  79556. _this._textureMatrix = BABYLON.Matrix.Identity();
  79557. _this.name = url;
  79558. _this.url = url;
  79559. _this.hasAlpha = false;
  79560. _this.isCube = false;
  79561. _this.is3D = _this._engine.webGLVersion > 1;
  79562. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79563. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79564. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79565. _this.anisotropicFilteringLevel = 1;
  79566. _this._texture = _this._getFromCache(url, true);
  79567. if (!_this._texture) {
  79568. if (!scene.useDelayedTextureLoading) {
  79569. _this.loadTexture();
  79570. }
  79571. else {
  79572. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79573. }
  79574. }
  79575. return _this;
  79576. }
  79577. /**
  79578. * Returns the texture matrix used in most of the material.
  79579. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  79580. */
  79581. ColorGradingTexture.prototype.getTextureMatrix = function () {
  79582. return this._textureMatrix;
  79583. };
  79584. /**
  79585. * Occurs when the file being loaded is a .3dl LUT file.
  79586. */
  79587. ColorGradingTexture.prototype.load3dlTexture = function () {
  79588. var engine = this._engine;
  79589. var texture;
  79590. if (engine.webGLVersion === 1) {
  79591. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79592. }
  79593. else {
  79594. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79595. }
  79596. this._texture = texture;
  79597. var callback = function (text) {
  79598. if (typeof text !== "string") {
  79599. return;
  79600. }
  79601. var data = null;
  79602. var tempData = null;
  79603. var line;
  79604. var lines = text.split('\n');
  79605. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  79606. var maxColor = 0;
  79607. for (var i = 0; i < lines.length; i++) {
  79608. line = lines[i];
  79609. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  79610. continue;
  79611. if (line.indexOf('#') === 0)
  79612. continue;
  79613. var words = line.split(" ");
  79614. if (size === 0) {
  79615. // Number of space + one
  79616. size = words.length;
  79617. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  79618. tempData = new Float32Array(size * size * size * 4);
  79619. continue;
  79620. }
  79621. if (size != 0) {
  79622. var r = Math.max(parseInt(words[0]), 0);
  79623. var g = Math.max(parseInt(words[1]), 0);
  79624. var b = Math.max(parseInt(words[2]), 0);
  79625. maxColor = Math.max(r, maxColor);
  79626. maxColor = Math.max(g, maxColor);
  79627. maxColor = Math.max(b, maxColor);
  79628. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  79629. if (tempData) {
  79630. tempData[pixelStorageIndex + 0] = r;
  79631. tempData[pixelStorageIndex + 1] = g;
  79632. tempData[pixelStorageIndex + 2] = b;
  79633. }
  79634. pixelIndexSlice++;
  79635. if (pixelIndexSlice % size == 0) {
  79636. pixelIndexH++;
  79637. pixelIndexSlice = 0;
  79638. if (pixelIndexH % size == 0) {
  79639. pixelIndexW++;
  79640. pixelIndexH = 0;
  79641. }
  79642. }
  79643. }
  79644. }
  79645. if (tempData && data) {
  79646. for (var i = 0; i < tempData.length; i++) {
  79647. if (i > 0 && (i + 1) % 4 === 0) {
  79648. data[i] = 255;
  79649. }
  79650. else {
  79651. var value = tempData[i];
  79652. data[i] = (value / maxColor * 255);
  79653. }
  79654. }
  79655. }
  79656. if (texture.is3D) {
  79657. texture.updateSize(size, size, size);
  79658. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79659. }
  79660. else {
  79661. texture.updateSize(size * size, size);
  79662. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79663. }
  79664. };
  79665. var scene = this.getScene();
  79666. if (scene) {
  79667. scene._loadFile(this.url, callback);
  79668. }
  79669. else {
  79670. this._engine._loadFile(this.url, callback);
  79671. }
  79672. return this._texture;
  79673. };
  79674. /**
  79675. * Starts the loading process of the texture.
  79676. */
  79677. ColorGradingTexture.prototype.loadTexture = function () {
  79678. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  79679. this.load3dlTexture();
  79680. }
  79681. };
  79682. /**
  79683. * Clones the color gradind texture.
  79684. */
  79685. ColorGradingTexture.prototype.clone = function () {
  79686. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  79687. // Base texture
  79688. newTexture.level = this.level;
  79689. return newTexture;
  79690. };
  79691. /**
  79692. * Called during delayed load for textures.
  79693. */
  79694. ColorGradingTexture.prototype.delayLoad = function () {
  79695. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79696. return;
  79697. }
  79698. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79699. this._texture = this._getFromCache(this.url, true);
  79700. if (!this._texture) {
  79701. this.loadTexture();
  79702. }
  79703. };
  79704. /**
  79705. * Parses a color grading texture serialized by Babylon.
  79706. * @param parsedTexture The texture information being parsedTexture
  79707. * @param scene The scene to load the texture in
  79708. * @param rootUrl The root url of the data assets to load
  79709. * @return A color gradind texture
  79710. */
  79711. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79712. var texture = null;
  79713. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79714. texture = new ColorGradingTexture(parsedTexture.name, scene);
  79715. texture.name = parsedTexture.name;
  79716. texture.level = parsedTexture.level;
  79717. }
  79718. return texture;
  79719. };
  79720. /**
  79721. * Serializes the LUT texture to json format.
  79722. */
  79723. ColorGradingTexture.prototype.serialize = function () {
  79724. if (!this.name) {
  79725. return null;
  79726. }
  79727. var serializationObject = {};
  79728. serializationObject.name = this.name;
  79729. serializationObject.level = this.level;
  79730. serializationObject.customType = "BABYLON.ColorGradingTexture";
  79731. return serializationObject;
  79732. };
  79733. /**
  79734. * Empty line regex stored for GC.
  79735. */
  79736. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  79737. return ColorGradingTexture;
  79738. }(BABYLON.BaseTexture));
  79739. BABYLON.ColorGradingTexture = ColorGradingTexture;
  79740. })(BABYLON || (BABYLON = {}));
  79741. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  79742. var BABYLON;
  79743. (function (BABYLON) {
  79744. /**
  79745. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79746. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79747. * 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;
  79748. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79749. */
  79750. var ColorCurves = /** @class */ (function () {
  79751. function ColorCurves() {
  79752. this._dirty = true;
  79753. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  79754. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  79755. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79756. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  79757. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79758. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  79759. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  79760. this._globalHue = 30;
  79761. this._globalDensity = 0;
  79762. this._globalSaturation = 0;
  79763. this._globalExposure = 0;
  79764. this._highlightsHue = 30;
  79765. this._highlightsDensity = 0;
  79766. this._highlightsSaturation = 0;
  79767. this._highlightsExposure = 0;
  79768. this._midtonesHue = 30;
  79769. this._midtonesDensity = 0;
  79770. this._midtonesSaturation = 0;
  79771. this._midtonesExposure = 0;
  79772. this._shadowsHue = 30;
  79773. this._shadowsDensity = 0;
  79774. this._shadowsSaturation = 0;
  79775. this._shadowsExposure = 0;
  79776. }
  79777. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  79778. /**
  79779. * Gets the global Hue value.
  79780. * 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).
  79781. */
  79782. get: function () {
  79783. return this._globalHue;
  79784. },
  79785. /**
  79786. * Sets the global Hue value.
  79787. * 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).
  79788. */
  79789. set: function (value) {
  79790. this._globalHue = value;
  79791. this._dirty = true;
  79792. },
  79793. enumerable: true,
  79794. configurable: true
  79795. });
  79796. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  79797. /**
  79798. * Gets the global Density value.
  79799. * 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.
  79800. * Values less than zero provide a filter of opposite hue.
  79801. */
  79802. get: function () {
  79803. return this._globalDensity;
  79804. },
  79805. /**
  79806. * Sets the global Density value.
  79807. * 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.
  79808. * Values less than zero provide a filter of opposite hue.
  79809. */
  79810. set: function (value) {
  79811. this._globalDensity = value;
  79812. this._dirty = true;
  79813. },
  79814. enumerable: true,
  79815. configurable: true
  79816. });
  79817. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  79818. /**
  79819. * Gets the global Saturation value.
  79820. * 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.
  79821. */
  79822. get: function () {
  79823. return this._globalSaturation;
  79824. },
  79825. /**
  79826. * Sets the global Saturation value.
  79827. * 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.
  79828. */
  79829. set: function (value) {
  79830. this._globalSaturation = value;
  79831. this._dirty = true;
  79832. },
  79833. enumerable: true,
  79834. configurable: true
  79835. });
  79836. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  79837. /**
  79838. * Gets the global Exposure value.
  79839. * 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.
  79840. */
  79841. get: function () {
  79842. return this._globalExposure;
  79843. },
  79844. /**
  79845. * Sets the global Exposure value.
  79846. * 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.
  79847. */
  79848. set: function (value) {
  79849. this._globalExposure = value;
  79850. this._dirty = true;
  79851. },
  79852. enumerable: true,
  79853. configurable: true
  79854. });
  79855. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  79856. /**
  79857. * Gets the highlights Hue value.
  79858. * 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).
  79859. */
  79860. get: function () {
  79861. return this._highlightsHue;
  79862. },
  79863. /**
  79864. * Sets the highlights Hue value.
  79865. * 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).
  79866. */
  79867. set: function (value) {
  79868. this._highlightsHue = value;
  79869. this._dirty = true;
  79870. },
  79871. enumerable: true,
  79872. configurable: true
  79873. });
  79874. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  79875. /**
  79876. * Gets the highlights Density value.
  79877. * 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.
  79878. * Values less than zero provide a filter of opposite hue.
  79879. */
  79880. get: function () {
  79881. return this._highlightsDensity;
  79882. },
  79883. /**
  79884. * Sets the highlights Density value.
  79885. * 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.
  79886. * Values less than zero provide a filter of opposite hue.
  79887. */
  79888. set: function (value) {
  79889. this._highlightsDensity = value;
  79890. this._dirty = true;
  79891. },
  79892. enumerable: true,
  79893. configurable: true
  79894. });
  79895. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  79896. /**
  79897. * Gets the highlights Saturation value.
  79898. * 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.
  79899. */
  79900. get: function () {
  79901. return this._highlightsSaturation;
  79902. },
  79903. /**
  79904. * Sets the highlights Saturation value.
  79905. * 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.
  79906. */
  79907. set: function (value) {
  79908. this._highlightsSaturation = value;
  79909. this._dirty = true;
  79910. },
  79911. enumerable: true,
  79912. configurable: true
  79913. });
  79914. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  79915. /**
  79916. * Gets the highlights Exposure value.
  79917. * 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.
  79918. */
  79919. get: function () {
  79920. return this._highlightsExposure;
  79921. },
  79922. /**
  79923. * Sets the highlights Exposure value.
  79924. * 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.
  79925. */
  79926. set: function (value) {
  79927. this._highlightsExposure = value;
  79928. this._dirty = true;
  79929. },
  79930. enumerable: true,
  79931. configurable: true
  79932. });
  79933. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  79934. /**
  79935. * Gets the midtones Hue value.
  79936. * 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).
  79937. */
  79938. get: function () {
  79939. return this._midtonesHue;
  79940. },
  79941. /**
  79942. * Sets the midtones Hue value.
  79943. * 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).
  79944. */
  79945. set: function (value) {
  79946. this._midtonesHue = value;
  79947. this._dirty = true;
  79948. },
  79949. enumerable: true,
  79950. configurable: true
  79951. });
  79952. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  79953. /**
  79954. * Gets the midtones Density value.
  79955. * 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.
  79956. * Values less than zero provide a filter of opposite hue.
  79957. */
  79958. get: function () {
  79959. return this._midtonesDensity;
  79960. },
  79961. /**
  79962. * Sets the midtones Density value.
  79963. * 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.
  79964. * Values less than zero provide a filter of opposite hue.
  79965. */
  79966. set: function (value) {
  79967. this._midtonesDensity = value;
  79968. this._dirty = true;
  79969. },
  79970. enumerable: true,
  79971. configurable: true
  79972. });
  79973. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  79974. /**
  79975. * Gets the midtones Saturation value.
  79976. * 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.
  79977. */
  79978. get: function () {
  79979. return this._midtonesSaturation;
  79980. },
  79981. /**
  79982. * Sets the midtones Saturation value.
  79983. * 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.
  79984. */
  79985. set: function (value) {
  79986. this._midtonesSaturation = value;
  79987. this._dirty = true;
  79988. },
  79989. enumerable: true,
  79990. configurable: true
  79991. });
  79992. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  79993. /**
  79994. * Gets the midtones Exposure value.
  79995. * 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.
  79996. */
  79997. get: function () {
  79998. return this._midtonesExposure;
  79999. },
  80000. /**
  80001. * Sets the midtones Exposure value.
  80002. * 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.
  80003. */
  80004. set: function (value) {
  80005. this._midtonesExposure = value;
  80006. this._dirty = true;
  80007. },
  80008. enumerable: true,
  80009. configurable: true
  80010. });
  80011. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  80012. /**
  80013. * Gets the shadows Hue value.
  80014. * 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).
  80015. */
  80016. get: function () {
  80017. return this._shadowsHue;
  80018. },
  80019. /**
  80020. * Sets the shadows Hue value.
  80021. * 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).
  80022. */
  80023. set: function (value) {
  80024. this._shadowsHue = value;
  80025. this._dirty = true;
  80026. },
  80027. enumerable: true,
  80028. configurable: true
  80029. });
  80030. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  80031. /**
  80032. * Gets the shadows Density value.
  80033. * 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.
  80034. * Values less than zero provide a filter of opposite hue.
  80035. */
  80036. get: function () {
  80037. return this._shadowsDensity;
  80038. },
  80039. /**
  80040. * Sets the shadows Density value.
  80041. * 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.
  80042. * Values less than zero provide a filter of opposite hue.
  80043. */
  80044. set: function (value) {
  80045. this._shadowsDensity = value;
  80046. this._dirty = true;
  80047. },
  80048. enumerable: true,
  80049. configurable: true
  80050. });
  80051. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  80052. /**
  80053. * Gets the shadows Saturation value.
  80054. * 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.
  80055. */
  80056. get: function () {
  80057. return this._shadowsSaturation;
  80058. },
  80059. /**
  80060. * Sets the shadows Saturation value.
  80061. * 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.
  80062. */
  80063. set: function (value) {
  80064. this._shadowsSaturation = value;
  80065. this._dirty = true;
  80066. },
  80067. enumerable: true,
  80068. configurable: true
  80069. });
  80070. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  80071. /**
  80072. * Gets the shadows Exposure value.
  80073. * 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.
  80074. */
  80075. get: function () {
  80076. return this._shadowsExposure;
  80077. },
  80078. /**
  80079. * Sets the shadows Exposure value.
  80080. * 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.
  80081. */
  80082. set: function (value) {
  80083. this._shadowsExposure = value;
  80084. this._dirty = true;
  80085. },
  80086. enumerable: true,
  80087. configurable: true
  80088. });
  80089. ColorCurves.prototype.getClassName = function () {
  80090. return "ColorCurves";
  80091. };
  80092. /**
  80093. * Binds the color curves to the shader.
  80094. * @param colorCurves The color curve to bind
  80095. * @param effect The effect to bind to
  80096. */
  80097. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  80098. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  80099. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  80100. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  80101. if (colorCurves._dirty) {
  80102. colorCurves._dirty = false;
  80103. // Fill in global info.
  80104. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  80105. // Compute highlights info.
  80106. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  80107. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  80108. // Compute midtones info.
  80109. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  80110. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  80111. // Compute shadows info.
  80112. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  80113. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  80114. // Compute deltas (neutral is midtones).
  80115. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  80116. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  80117. }
  80118. if (effect) {
  80119. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  80120. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  80121. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  80122. }
  80123. };
  80124. /**
  80125. * Prepare the list of uniforms associated with the ColorCurves effects.
  80126. * @param uniformsList The list of uniforms used in the effect
  80127. */
  80128. ColorCurves.PrepareUniforms = function (uniformsList) {
  80129. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  80130. };
  80131. /**
  80132. * Returns color grading data based on a hue, density, saturation and exposure value.
  80133. * @param filterHue The hue of the color filter.
  80134. * @param filterDensity The density of the color filter.
  80135. * @param saturation The saturation.
  80136. * @param exposure The exposure.
  80137. * @param result The result data container.
  80138. */
  80139. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  80140. if (hue == null) {
  80141. return;
  80142. }
  80143. hue = ColorCurves.clamp(hue, 0, 360);
  80144. density = ColorCurves.clamp(density, -100, 100);
  80145. saturation = ColorCurves.clamp(saturation, -100, 100);
  80146. exposure = ColorCurves.clamp(exposure, -100, 100);
  80147. // Remap the slider/config filter density with non-linear mapping and also scale by half
  80148. // so that the maximum filter density is only 50% control. This provides fine control
  80149. // for small values and reasonable range.
  80150. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  80151. density *= 0.5;
  80152. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  80153. if (density < 0) {
  80154. density *= -1;
  80155. hue = (hue + 180) % 360;
  80156. }
  80157. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  80158. result.scaleToRef(2, result);
  80159. result.a = 1 + 0.01 * saturation;
  80160. };
  80161. /**
  80162. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  80163. * @param value The input slider value in range [-100,100].
  80164. * @returns Adjusted value.
  80165. */
  80166. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  80167. value /= 100;
  80168. var x = Math.abs(value);
  80169. x = Math.pow(x, 2);
  80170. if (value < 0) {
  80171. x *= -1;
  80172. }
  80173. x *= 100;
  80174. return x;
  80175. };
  80176. /**
  80177. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  80178. * @param hue The hue (H) input.
  80179. * @param saturation The saturation (S) input.
  80180. * @param brightness The brightness (B) input.
  80181. * @result An RGBA color represented as Vector4.
  80182. */
  80183. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  80184. var h = ColorCurves.clamp(hue, 0, 360);
  80185. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  80186. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  80187. if (s === 0) {
  80188. result.r = v;
  80189. result.g = v;
  80190. result.b = v;
  80191. }
  80192. else {
  80193. // sector 0 to 5
  80194. h /= 60;
  80195. var i = Math.floor(h);
  80196. // fractional part of h
  80197. var f = h - i;
  80198. var p = v * (1 - s);
  80199. var q = v * (1 - s * f);
  80200. var t = v * (1 - s * (1 - f));
  80201. switch (i) {
  80202. case 0:
  80203. result.r = v;
  80204. result.g = t;
  80205. result.b = p;
  80206. break;
  80207. case 1:
  80208. result.r = q;
  80209. result.g = v;
  80210. result.b = p;
  80211. break;
  80212. case 2:
  80213. result.r = p;
  80214. result.g = v;
  80215. result.b = t;
  80216. break;
  80217. case 3:
  80218. result.r = p;
  80219. result.g = q;
  80220. result.b = v;
  80221. break;
  80222. case 4:
  80223. result.r = t;
  80224. result.g = p;
  80225. result.b = v;
  80226. break;
  80227. default: // case 5:
  80228. result.r = v;
  80229. result.g = p;
  80230. result.b = q;
  80231. break;
  80232. }
  80233. }
  80234. result.a = 1;
  80235. };
  80236. /**
  80237. * Returns a value clamped between min and max
  80238. * @param value The value to clamp
  80239. * @param min The minimum of value
  80240. * @param max The maximum of value
  80241. * @returns The clamped value.
  80242. */
  80243. ColorCurves.clamp = function (value, min, max) {
  80244. return Math.min(Math.max(value, min), max);
  80245. };
  80246. /**
  80247. * Clones the current color curve instance.
  80248. * @return The cloned curves
  80249. */
  80250. ColorCurves.prototype.clone = function () {
  80251. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  80252. };
  80253. /**
  80254. * Serializes the current color curve instance to a json representation.
  80255. * @return a JSON representation
  80256. */
  80257. ColorCurves.prototype.serialize = function () {
  80258. return BABYLON.SerializationHelper.Serialize(this);
  80259. };
  80260. /**
  80261. * Parses the color curve from a json representation.
  80262. * @param source the JSON source to parse
  80263. * @return The parsed curves
  80264. */
  80265. ColorCurves.Parse = function (source) {
  80266. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  80267. };
  80268. __decorate([
  80269. BABYLON.serialize()
  80270. ], ColorCurves.prototype, "_globalHue", void 0);
  80271. __decorate([
  80272. BABYLON.serialize()
  80273. ], ColorCurves.prototype, "_globalDensity", void 0);
  80274. __decorate([
  80275. BABYLON.serialize()
  80276. ], ColorCurves.prototype, "_globalSaturation", void 0);
  80277. __decorate([
  80278. BABYLON.serialize()
  80279. ], ColorCurves.prototype, "_globalExposure", void 0);
  80280. __decorate([
  80281. BABYLON.serialize()
  80282. ], ColorCurves.prototype, "_highlightsHue", void 0);
  80283. __decorate([
  80284. BABYLON.serialize()
  80285. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  80286. __decorate([
  80287. BABYLON.serialize()
  80288. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  80289. __decorate([
  80290. BABYLON.serialize()
  80291. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  80292. __decorate([
  80293. BABYLON.serialize()
  80294. ], ColorCurves.prototype, "_midtonesHue", void 0);
  80295. __decorate([
  80296. BABYLON.serialize()
  80297. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  80298. __decorate([
  80299. BABYLON.serialize()
  80300. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  80301. __decorate([
  80302. BABYLON.serialize()
  80303. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  80304. return ColorCurves;
  80305. }());
  80306. BABYLON.ColorCurves = ColorCurves;
  80307. })(BABYLON || (BABYLON = {}));
  80308. //# sourceMappingURL=babylon.colorCurves.js.map
  80309. var BABYLON;
  80310. (function (BABYLON) {
  80311. var RefractionPostProcess = /** @class */ (function (_super) {
  80312. __extends(RefractionPostProcess, _super);
  80313. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  80314. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  80315. _this.color = color;
  80316. _this.depth = depth;
  80317. _this.colorLevel = colorLevel;
  80318. _this._ownRefractionTexture = true;
  80319. _this.onActivateObservable.add(function (cam) {
  80320. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  80321. });
  80322. _this.onApplyObservable.add(function (effect) {
  80323. effect.setColor3("baseColor", _this.color);
  80324. effect.setFloat("depth", _this.depth);
  80325. effect.setFloat("colorLevel", _this.colorLevel);
  80326. effect.setTexture("refractionSampler", _this._refTexture);
  80327. });
  80328. return _this;
  80329. }
  80330. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  80331. /**
  80332. * Gets or sets the refraction texture
  80333. * Please note that you are responsible for disposing the texture if you set it manually
  80334. */
  80335. get: function () {
  80336. return this._refTexture;
  80337. },
  80338. set: function (value) {
  80339. if (this._refTexture && this._ownRefractionTexture) {
  80340. this._refTexture.dispose();
  80341. }
  80342. this._refTexture = value;
  80343. this._ownRefractionTexture = false;
  80344. },
  80345. enumerable: true,
  80346. configurable: true
  80347. });
  80348. // Methods
  80349. RefractionPostProcess.prototype.dispose = function (camera) {
  80350. if (this._refTexture && this._ownRefractionTexture) {
  80351. this._refTexture.dispose();
  80352. this._refTexture = null;
  80353. }
  80354. _super.prototype.dispose.call(this, camera);
  80355. };
  80356. return RefractionPostProcess;
  80357. }(BABYLON.PostProcess));
  80358. BABYLON.RefractionPostProcess = RefractionPostProcess;
  80359. })(BABYLON || (BABYLON = {}));
  80360. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  80361. var BABYLON;
  80362. (function (BABYLON) {
  80363. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  80364. __extends(BlackAndWhitePostProcess, _super);
  80365. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  80366. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  80367. _this.degree = 1;
  80368. _this.onApplyObservable.add(function (effect) {
  80369. effect.setFloat("degree", _this.degree);
  80370. });
  80371. return _this;
  80372. }
  80373. return BlackAndWhitePostProcess;
  80374. }(BABYLON.PostProcess));
  80375. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  80376. })(BABYLON || (BABYLON = {}));
  80377. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  80378. var BABYLON;
  80379. (function (BABYLON) {
  80380. /**
  80381. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  80382. * input texture to perform effects such as edge detection or sharpening
  80383. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80384. */
  80385. var ConvolutionPostProcess = /** @class */ (function (_super) {
  80386. __extends(ConvolutionPostProcess, _super);
  80387. /**
  80388. * Creates a new instance ConvolutionPostProcess
  80389. * @param name The name of the effect.
  80390. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  80391. * @param options The required width/height ratio to downsize to before computing the render pass.
  80392. * @param camera The camera to apply the render pass to.
  80393. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80394. * @param engine The engine which the post process will be applied. (default: current engine)
  80395. * @param reusable If the post process can be reused on the same frame. (default: false)
  80396. * @param textureType Type of textures used when performing the post process. (default: 0)
  80397. */
  80398. function ConvolutionPostProcess(name,
  80399. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  80400. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  80401. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80402. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80403. _this.kernel = kernel;
  80404. _this.onApply = function (effect) {
  80405. effect.setFloat2("screenSize", _this.width, _this.height);
  80406. effect.setArray("kernel", _this.kernel);
  80407. };
  80408. return _this;
  80409. }
  80410. // Statics
  80411. /**
  80412. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80413. */
  80414. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  80415. /**
  80416. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80417. */
  80418. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  80419. /**
  80420. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80421. */
  80422. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  80423. /**
  80424. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80425. */
  80426. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  80427. /**
  80428. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80429. */
  80430. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  80431. /**
  80432. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80433. */
  80434. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  80435. return ConvolutionPostProcess;
  80436. }(BABYLON.PostProcess));
  80437. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  80438. })(BABYLON || (BABYLON = {}));
  80439. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  80440. var BABYLON;
  80441. (function (BABYLON) {
  80442. var FilterPostProcess = /** @class */ (function (_super) {
  80443. __extends(FilterPostProcess, _super);
  80444. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  80445. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  80446. _this.kernelMatrix = kernelMatrix;
  80447. _this.onApply = function (effect) {
  80448. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  80449. };
  80450. return _this;
  80451. }
  80452. return FilterPostProcess;
  80453. }(BABYLON.PostProcess));
  80454. BABYLON.FilterPostProcess = FilterPostProcess;
  80455. })(BABYLON || (BABYLON = {}));
  80456. //# sourceMappingURL=babylon.filterPostProcess.js.map
  80457. var BABYLON;
  80458. (function (BABYLON) {
  80459. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  80460. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  80461. __extends(VolumetricLightScatteringPostProcess, _super);
  80462. /**
  80463. * @constructor
  80464. * @param {string} name - The post-process name
  80465. * @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)
  80466. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  80467. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  80468. * @param {number} samples - The post-process quality, default 100
  80469. * @param {number} samplingMode - The post-process filtering mode
  80470. * @param {BABYLON.Engine} engine - The babylon engine
  80471. * @param {boolean} reusable - If the post-process is reusable
  80472. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  80473. */
  80474. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  80475. if (samples === void 0) { samples = 100; }
  80476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80477. 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;
  80478. _this._screenCoordinates = BABYLON.Vector2.Zero();
  80479. /**
  80480. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  80481. */
  80482. _this.customMeshPosition = BABYLON.Vector3.Zero();
  80483. /**
  80484. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  80485. */
  80486. _this.useCustomMeshPosition = false;
  80487. /**
  80488. * If the post-process should inverse the light scattering direction
  80489. */
  80490. _this.invert = true;
  80491. /**
  80492. * Array containing the excluded meshes not rendered in the internal pass
  80493. */
  80494. _this.excludedMeshes = new Array();
  80495. /**
  80496. * Controls the overall intensity of the post-process
  80497. */
  80498. _this.exposure = 0.3;
  80499. /**
  80500. * Dissipates each sample's contribution in range [0, 1]
  80501. */
  80502. _this.decay = 0.96815;
  80503. /**
  80504. * Controls the overall intensity of each sample
  80505. */
  80506. _this.weight = 0.58767;
  80507. /**
  80508. * Controls the density of each sample
  80509. */
  80510. _this.density = 0.926;
  80511. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  80512. engine = scene.getEngine();
  80513. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  80514. // Configure mesh
  80515. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  80516. // Configure
  80517. _this._createPass(scene, ratio.passRatio || ratio);
  80518. _this.onActivate = function (camera) {
  80519. if (!_this.isSupported) {
  80520. _this.dispose(camera);
  80521. }
  80522. _this.onActivate = null;
  80523. };
  80524. _this.onApplyObservable.add(function (effect) {
  80525. _this._updateMeshScreenCoordinates(scene);
  80526. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  80527. effect.setFloat("exposure", _this.exposure);
  80528. effect.setFloat("decay", _this.decay);
  80529. effect.setFloat("weight", _this.weight);
  80530. effect.setFloat("density", _this.density);
  80531. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  80532. });
  80533. return _this;
  80534. }
  80535. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  80536. get: function () {
  80537. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  80538. return false;
  80539. },
  80540. set: function (useDiffuseColor) {
  80541. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  80542. },
  80543. enumerable: true,
  80544. configurable: true
  80545. });
  80546. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  80547. return "VolumetricLightScatteringPostProcess";
  80548. };
  80549. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  80550. var mesh = subMesh.getMesh();
  80551. // Render this.mesh as default
  80552. if (mesh === this.mesh && mesh.material) {
  80553. return mesh.material.isReady(mesh);
  80554. }
  80555. var defines = [];
  80556. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80557. var material = subMesh.getMaterial();
  80558. // Alpha test
  80559. if (material) {
  80560. if (material.needAlphaTesting()) {
  80561. defines.push("#define ALPHATEST");
  80562. }
  80563. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80564. attribs.push(BABYLON.VertexBuffer.UVKind);
  80565. defines.push("#define UV1");
  80566. }
  80567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80568. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80569. defines.push("#define UV2");
  80570. }
  80571. }
  80572. // Bones
  80573. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80574. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80575. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80576. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80577. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80578. }
  80579. else {
  80580. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80581. }
  80582. // Instances
  80583. if (useInstances) {
  80584. defines.push("#define INSTANCES");
  80585. attribs.push("world0");
  80586. attribs.push("world1");
  80587. attribs.push("world2");
  80588. attribs.push("world3");
  80589. }
  80590. // Get correct effect
  80591. var join = defines.join("\n");
  80592. if (this._cachedDefines !== join) {
  80593. this._cachedDefines = join;
  80594. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  80595. }
  80596. return this._volumetricLightScatteringPass.isReady();
  80597. };
  80598. /**
  80599. * Sets the new light position for light scattering effect
  80600. * @param {BABYLON.Vector3} The new custom light position
  80601. */
  80602. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  80603. this.customMeshPosition = position;
  80604. };
  80605. /**
  80606. * Returns the light position for light scattering effect
  80607. * @return {BABYLON.Vector3} The custom light position
  80608. */
  80609. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  80610. return this.customMeshPosition;
  80611. };
  80612. /**
  80613. * Disposes the internal assets and detaches the post-process from the camera
  80614. */
  80615. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  80616. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  80617. if (rttIndex !== -1) {
  80618. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  80619. }
  80620. this._volumetricLightScatteringRTT.dispose();
  80621. _super.prototype.dispose.call(this, camera);
  80622. };
  80623. /**
  80624. * Returns the render target texture used by the post-process
  80625. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  80626. */
  80627. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  80628. return this._volumetricLightScatteringRTT;
  80629. };
  80630. // Private methods
  80631. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  80632. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  80633. return true;
  80634. }
  80635. return false;
  80636. };
  80637. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  80638. var _this = this;
  80639. var engine = scene.getEngine();
  80640. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80641. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80642. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80643. this._volumetricLightScatteringRTT.renderList = null;
  80644. this._volumetricLightScatteringRTT.renderParticles = false;
  80645. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  80646. var camera = this.getCamera();
  80647. if (camera) {
  80648. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80649. }
  80650. else {
  80651. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80652. }
  80653. // Custom render function for submeshes
  80654. var renderSubMesh = function (subMesh) {
  80655. var mesh = subMesh.getRenderingMesh();
  80656. if (_this._meshExcluded(mesh)) {
  80657. return;
  80658. }
  80659. var material = subMesh.getMaterial();
  80660. if (!material) {
  80661. return;
  80662. }
  80663. var scene = mesh.getScene();
  80664. var engine = scene.getEngine();
  80665. // Culling
  80666. engine.setState(material.backFaceCulling);
  80667. // Managing instances
  80668. var batch = mesh._getInstancesRenderList(subMesh._id);
  80669. if (batch.mustReturn) {
  80670. return;
  80671. }
  80672. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80673. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  80674. var effect = _this._volumetricLightScatteringPass;
  80675. if (mesh === _this.mesh) {
  80676. if (subMesh.effect) {
  80677. effect = subMesh.effect;
  80678. }
  80679. else {
  80680. effect = material.getEffect();
  80681. }
  80682. }
  80683. engine.enableEffect(effect);
  80684. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  80685. if (mesh === _this.mesh) {
  80686. material.bind(mesh.getWorldMatrix(), mesh);
  80687. }
  80688. else {
  80689. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  80690. // Alpha test
  80691. if (material && material.needAlphaTesting()) {
  80692. var alphaTexture = material.getAlphaTestTexture();
  80693. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  80694. if (alphaTexture) {
  80695. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80696. }
  80697. }
  80698. // Bones
  80699. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80700. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80701. }
  80702. }
  80703. // Draw
  80704. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  80705. }
  80706. };
  80707. // Render target texture callbacks
  80708. var savedSceneClearColor;
  80709. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  80710. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  80711. savedSceneClearColor = scene.clearColor;
  80712. scene.clearColor = sceneClearColor;
  80713. });
  80714. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  80715. scene.clearColor = savedSceneClearColor;
  80716. });
  80717. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80718. var engine = scene.getEngine();
  80719. var index;
  80720. if (depthOnlySubMeshes.length) {
  80721. engine.setColorWrite(false);
  80722. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80723. renderSubMesh(depthOnlySubMeshes.data[index]);
  80724. }
  80725. engine.setColorWrite(true);
  80726. }
  80727. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80728. renderSubMesh(opaqueSubMeshes.data[index]);
  80729. }
  80730. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80731. renderSubMesh(alphaTestSubMeshes.data[index]);
  80732. }
  80733. if (transparentSubMeshes.length) {
  80734. // Sort sub meshes
  80735. for (index = 0; index < transparentSubMeshes.length; index++) {
  80736. var submesh = transparentSubMeshes.data[index];
  80737. var boundingInfo = submesh.getBoundingInfo();
  80738. if (boundingInfo && scene.activeCamera) {
  80739. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  80740. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  80741. }
  80742. }
  80743. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  80744. sortedArray.sort(function (a, b) {
  80745. // Alpha index first
  80746. if (a._alphaIndex > b._alphaIndex) {
  80747. return 1;
  80748. }
  80749. if (a._alphaIndex < b._alphaIndex) {
  80750. return -1;
  80751. }
  80752. // Then distance to camera
  80753. if (a._distanceToCamera < b._distanceToCamera) {
  80754. return 1;
  80755. }
  80756. if (a._distanceToCamera > b._distanceToCamera) {
  80757. return -1;
  80758. }
  80759. return 0;
  80760. });
  80761. // Render sub meshes
  80762. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  80763. for (index = 0; index < sortedArray.length; index++) {
  80764. renderSubMesh(sortedArray[index]);
  80765. }
  80766. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80767. }
  80768. };
  80769. };
  80770. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  80771. var transform = scene.getTransformMatrix();
  80772. var meshPosition;
  80773. if (this.useCustomMeshPosition) {
  80774. meshPosition = this.customMeshPosition;
  80775. }
  80776. else if (this.attachedNode) {
  80777. meshPosition = this.attachedNode.position;
  80778. }
  80779. else {
  80780. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  80781. }
  80782. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  80783. this._screenCoordinates.x = pos.x / this._viewPort.width;
  80784. this._screenCoordinates.y = pos.y / this._viewPort.height;
  80785. if (this.invert)
  80786. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  80787. };
  80788. // Static methods
  80789. /**
  80790. * Creates a default mesh for the Volumeric Light Scattering post-process
  80791. * @param {string} The mesh name
  80792. * @param {BABYLON.Scene} The scene where to create the mesh
  80793. * @return {BABYLON.Mesh} the default mesh
  80794. */
  80795. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  80796. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  80797. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  80798. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  80799. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  80800. mesh.material = material;
  80801. return mesh;
  80802. };
  80803. __decorate([
  80804. BABYLON.serializeAsVector3()
  80805. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  80806. __decorate([
  80807. BABYLON.serialize()
  80808. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  80809. __decorate([
  80810. BABYLON.serialize()
  80811. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  80812. __decorate([
  80813. BABYLON.serializeAsMeshReference()
  80814. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  80815. __decorate([
  80816. BABYLON.serialize()
  80817. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  80818. __decorate([
  80819. BABYLON.serialize()
  80820. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  80821. __decorate([
  80822. BABYLON.serialize()
  80823. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  80824. __decorate([
  80825. BABYLON.serialize()
  80826. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  80827. __decorate([
  80828. BABYLON.serialize()
  80829. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  80830. return VolumetricLightScatteringPostProcess;
  80831. }(BABYLON.PostProcess));
  80832. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  80833. })(BABYLON || (BABYLON = {}));
  80834. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  80835. //
  80836. // This post-process allows the modification of rendered colors by using
  80837. // a 'look-up table' (LUT). This effect is also called Color Grading.
  80838. //
  80839. // The object needs to be provided an url to a texture containing the color
  80840. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  80841. // Use an image editing software to tweak the LUT to match your needs.
  80842. //
  80843. // For an example of a color LUT, see here:
  80844. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  80845. // For explanations on color grading, see here:
  80846. // http://udn.epicgames.com/Three/ColorGrading.html
  80847. //
  80848. var BABYLON;
  80849. (function (BABYLON) {
  80850. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  80851. __extends(ColorCorrectionPostProcess, _super);
  80852. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  80853. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  80854. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80855. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  80856. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80857. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80858. _this.onApply = function (effect) {
  80859. effect.setTexture("colorTable", _this._colorTableTexture);
  80860. };
  80861. return _this;
  80862. }
  80863. return ColorCorrectionPostProcess;
  80864. }(BABYLON.PostProcess));
  80865. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  80866. })(BABYLON || (BABYLON = {}));
  80867. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  80868. var BABYLON;
  80869. (function (BABYLON) {
  80870. /** Defines operator used for tonemapping */
  80871. var TonemappingOperator;
  80872. (function (TonemappingOperator) {
  80873. /** Hable */
  80874. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  80875. /** Reinhard */
  80876. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  80877. /** HejiDawson */
  80878. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  80879. /** Photographic */
  80880. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  80881. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  80882. ;
  80883. /**
  80884. * Defines a post process to apply tone mapping
  80885. */
  80886. var TonemapPostProcess = /** @class */ (function (_super) {
  80887. __extends(TonemapPostProcess, _super);
  80888. /**
  80889. * Creates a new TonemapPostProcess
  80890. * @param name defines the name of the postprocess
  80891. * @param _operator defines the operator to use
  80892. * @param exposureAdjustment defines the required exposure adjustement
  80893. * @param camera defines the camera to use (can be null)
  80894. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  80895. * @param engine defines the hosting engine (can be ignore if camera is set)
  80896. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  80897. */
  80898. function TonemapPostProcess(name, _operator,
  80899. /** Defines the required exposure adjustement */
  80900. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  80901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80902. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80903. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  80904. _this._operator = _operator;
  80905. _this.exposureAdjustment = exposureAdjustment;
  80906. var defines = "#define ";
  80907. if (_this._operator === TonemappingOperator.Hable)
  80908. defines += "HABLE_TONEMAPPING";
  80909. else if (_this._operator === TonemappingOperator.Reinhard)
  80910. defines += "REINHARD_TONEMAPPING";
  80911. else if (_this._operator === TonemappingOperator.HejiDawson)
  80912. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  80913. else if (_this._operator === TonemappingOperator.Photographic)
  80914. defines += "PHOTOGRAPHIC_TONEMAPPING";
  80915. //sadly a second call to create the effect.
  80916. _this.updateEffect(defines);
  80917. _this.onApply = function (effect) {
  80918. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  80919. };
  80920. return _this;
  80921. }
  80922. return TonemapPostProcess;
  80923. }(BABYLON.PostProcess));
  80924. BABYLON.TonemapPostProcess = TonemapPostProcess;
  80925. })(BABYLON || (BABYLON = {}));
  80926. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  80927. var BABYLON;
  80928. (function (BABYLON) {
  80929. var DisplayPassPostProcess = /** @class */ (function (_super) {
  80930. __extends(DisplayPassPostProcess, _super);
  80931. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  80932. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  80933. }
  80934. return DisplayPassPostProcess;
  80935. }(BABYLON.PostProcess));
  80936. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  80937. })(BABYLON || (BABYLON = {}));
  80938. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  80939. var BABYLON;
  80940. (function (BABYLON) {
  80941. var HighlightsPostProcess = /** @class */ (function (_super) {
  80942. __extends(HighlightsPostProcess, _super);
  80943. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80944. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80945. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80946. }
  80947. return HighlightsPostProcess;
  80948. }(BABYLON.PostProcess));
  80949. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  80950. })(BABYLON || (BABYLON = {}));
  80951. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  80952. var BABYLON;
  80953. (function (BABYLON) {
  80954. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  80955. __extends(ImageProcessingPostProcess, _super);
  80956. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  80957. if (camera === void 0) { camera = null; }
  80958. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80959. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  80960. _this._fromLinearSpace = true;
  80961. /**
  80962. * Defines cache preventing GC.
  80963. */
  80964. _this._defines = {
  80965. IMAGEPROCESSING: false,
  80966. VIGNETTE: false,
  80967. VIGNETTEBLENDMODEMULTIPLY: false,
  80968. VIGNETTEBLENDMODEOPAQUE: false,
  80969. TONEMAPPING: false,
  80970. CONTRAST: false,
  80971. COLORCURVES: false,
  80972. COLORGRADING: false,
  80973. COLORGRADING3D: false,
  80974. FROMLINEARSPACE: false,
  80975. SAMPLER3DGREENDEPTH: false,
  80976. SAMPLER3DBGRMAP: false,
  80977. IMAGEPROCESSINGPOSTPROCESS: false,
  80978. EXPOSURE: false,
  80979. };
  80980. // Setup the configuration as forced by the constructor. This would then not force the
  80981. // scene materials output in linear space and let untouched the default forward pass.
  80982. if (imageProcessingConfiguration) {
  80983. imageProcessingConfiguration.applyByPostProcess = true;
  80984. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  80985. // This will cause the shader to be compiled
  80986. _this.fromLinearSpace = false;
  80987. }
  80988. // Setup the default processing configuration to the scene.
  80989. else {
  80990. _this._attachImageProcessingConfiguration(null, true);
  80991. _this.imageProcessingConfiguration.applyByPostProcess = true;
  80992. }
  80993. _this.onApply = function (effect) {
  80994. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  80995. };
  80996. return _this;
  80997. }
  80998. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  80999. /**
  81000. * Gets the image processing configuration used either in this material.
  81001. */
  81002. get: function () {
  81003. return this._imageProcessingConfiguration;
  81004. },
  81005. /**
  81006. * Sets the Default image processing configuration used either in the this material.
  81007. *
  81008. * If sets to null, the scene one is in use.
  81009. */
  81010. set: function (value) {
  81011. this._attachImageProcessingConfiguration(value);
  81012. },
  81013. enumerable: true,
  81014. configurable: true
  81015. });
  81016. /**
  81017. * Attaches a new image processing configuration to the PBR Material.
  81018. * @param configuration
  81019. */
  81020. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  81021. var _this = this;
  81022. if (doNotBuild === void 0) { doNotBuild = false; }
  81023. if (configuration === this._imageProcessingConfiguration) {
  81024. return;
  81025. }
  81026. // Detaches observer.
  81027. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81028. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81029. }
  81030. // Pick the scene configuration if needed.
  81031. if (!configuration) {
  81032. var scene = null;
  81033. var engine = this.getEngine();
  81034. var camera = this.getCamera();
  81035. if (camera) {
  81036. scene = camera.getScene();
  81037. }
  81038. else if (engine && engine.scenes) {
  81039. var scenes = engine.scenes;
  81040. scene = scenes[scenes.length - 1];
  81041. }
  81042. else {
  81043. scene = BABYLON.Engine.LastCreatedScene;
  81044. }
  81045. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  81046. }
  81047. else {
  81048. this._imageProcessingConfiguration = configuration;
  81049. }
  81050. // Attaches observer.
  81051. if (this._imageProcessingConfiguration) {
  81052. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  81053. _this._updateParameters();
  81054. });
  81055. }
  81056. // Ensure the effect will be rebuilt.
  81057. if (!doNotBuild) {
  81058. this._updateParameters();
  81059. }
  81060. };
  81061. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  81062. /**
  81063. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  81064. */
  81065. get: function () {
  81066. return this.imageProcessingConfiguration.colorCurves;
  81067. },
  81068. /**
  81069. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  81070. */
  81071. set: function (value) {
  81072. this.imageProcessingConfiguration.colorCurves = value;
  81073. },
  81074. enumerable: true,
  81075. configurable: true
  81076. });
  81077. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  81078. /**
  81079. * Gets wether the color curves effect is enabled.
  81080. */
  81081. get: function () {
  81082. return this.imageProcessingConfiguration.colorCurvesEnabled;
  81083. },
  81084. /**
  81085. * Sets wether the color curves effect is enabled.
  81086. */
  81087. set: function (value) {
  81088. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  81089. },
  81090. enumerable: true,
  81091. configurable: true
  81092. });
  81093. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  81094. /**
  81095. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  81096. */
  81097. get: function () {
  81098. return this.imageProcessingConfiguration.colorGradingTexture;
  81099. },
  81100. /**
  81101. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  81102. */
  81103. set: function (value) {
  81104. this.imageProcessingConfiguration.colorGradingTexture = value;
  81105. },
  81106. enumerable: true,
  81107. configurable: true
  81108. });
  81109. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  81110. /**
  81111. * Gets wether the color grading effect is enabled.
  81112. */
  81113. get: function () {
  81114. return this.imageProcessingConfiguration.colorGradingEnabled;
  81115. },
  81116. /**
  81117. * Gets wether the color grading effect is enabled.
  81118. */
  81119. set: function (value) {
  81120. this.imageProcessingConfiguration.colorGradingEnabled = value;
  81121. },
  81122. enumerable: true,
  81123. configurable: true
  81124. });
  81125. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  81126. /**
  81127. * Gets exposure used in the effect.
  81128. */
  81129. get: function () {
  81130. return this.imageProcessingConfiguration.exposure;
  81131. },
  81132. /**
  81133. * Sets exposure used in the effect.
  81134. */
  81135. set: function (value) {
  81136. this.imageProcessingConfiguration.exposure = value;
  81137. },
  81138. enumerable: true,
  81139. configurable: true
  81140. });
  81141. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  81142. /**
  81143. * Gets wether tonemapping is enabled or not.
  81144. */
  81145. get: function () {
  81146. return this._imageProcessingConfiguration.toneMappingEnabled;
  81147. },
  81148. /**
  81149. * Sets wether tonemapping is enabled or not
  81150. */
  81151. set: function (value) {
  81152. this._imageProcessingConfiguration.toneMappingEnabled = value;
  81153. },
  81154. enumerable: true,
  81155. configurable: true
  81156. });
  81157. ;
  81158. ;
  81159. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  81160. /**
  81161. * Gets contrast used in the effect.
  81162. */
  81163. get: function () {
  81164. return this.imageProcessingConfiguration.contrast;
  81165. },
  81166. /**
  81167. * Sets contrast used in the effect.
  81168. */
  81169. set: function (value) {
  81170. this.imageProcessingConfiguration.contrast = value;
  81171. },
  81172. enumerable: true,
  81173. configurable: true
  81174. });
  81175. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  81176. /**
  81177. * Gets Vignette stretch size.
  81178. */
  81179. get: function () {
  81180. return this.imageProcessingConfiguration.vignetteStretch;
  81181. },
  81182. /**
  81183. * Sets Vignette stretch size.
  81184. */
  81185. set: function (value) {
  81186. this.imageProcessingConfiguration.vignetteStretch = value;
  81187. },
  81188. enumerable: true,
  81189. configurable: true
  81190. });
  81191. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  81192. /**
  81193. * Gets Vignette centre X Offset.
  81194. */
  81195. get: function () {
  81196. return this.imageProcessingConfiguration.vignetteCentreX;
  81197. },
  81198. /**
  81199. * Sets Vignette centre X Offset.
  81200. */
  81201. set: function (value) {
  81202. this.imageProcessingConfiguration.vignetteCentreX = value;
  81203. },
  81204. enumerable: true,
  81205. configurable: true
  81206. });
  81207. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  81208. /**
  81209. * Gets Vignette centre Y Offset.
  81210. */
  81211. get: function () {
  81212. return this.imageProcessingConfiguration.vignetteCentreY;
  81213. },
  81214. /**
  81215. * Sets Vignette centre Y Offset.
  81216. */
  81217. set: function (value) {
  81218. this.imageProcessingConfiguration.vignetteCentreY = value;
  81219. },
  81220. enumerable: true,
  81221. configurable: true
  81222. });
  81223. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  81224. /**
  81225. * Gets Vignette weight or intensity of the vignette effect.
  81226. */
  81227. get: function () {
  81228. return this.imageProcessingConfiguration.vignetteWeight;
  81229. },
  81230. /**
  81231. * Sets Vignette weight or intensity of the vignette effect.
  81232. */
  81233. set: function (value) {
  81234. this.imageProcessingConfiguration.vignetteWeight = value;
  81235. },
  81236. enumerable: true,
  81237. configurable: true
  81238. });
  81239. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  81240. /**
  81241. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81242. * if vignetteEnabled is set to true.
  81243. */
  81244. get: function () {
  81245. return this.imageProcessingConfiguration.vignetteColor;
  81246. },
  81247. /**
  81248. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81249. * if vignetteEnabled is set to true.
  81250. */
  81251. set: function (value) {
  81252. this.imageProcessingConfiguration.vignetteColor = value;
  81253. },
  81254. enumerable: true,
  81255. configurable: true
  81256. });
  81257. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  81258. /**
  81259. * Gets Camera field of view used by the Vignette effect.
  81260. */
  81261. get: function () {
  81262. return this.imageProcessingConfiguration.vignetteCameraFov;
  81263. },
  81264. /**
  81265. * Sets Camera field of view used by the Vignette effect.
  81266. */
  81267. set: function (value) {
  81268. this.imageProcessingConfiguration.vignetteCameraFov = value;
  81269. },
  81270. enumerable: true,
  81271. configurable: true
  81272. });
  81273. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  81274. /**
  81275. * Gets the vignette blend mode allowing different kind of effect.
  81276. */
  81277. get: function () {
  81278. return this.imageProcessingConfiguration.vignetteBlendMode;
  81279. },
  81280. /**
  81281. * Sets the vignette blend mode allowing different kind of effect.
  81282. */
  81283. set: function (value) {
  81284. this.imageProcessingConfiguration.vignetteBlendMode = value;
  81285. },
  81286. enumerable: true,
  81287. configurable: true
  81288. });
  81289. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  81290. /**
  81291. * Gets wether the vignette effect is enabled.
  81292. */
  81293. get: function () {
  81294. return this.imageProcessingConfiguration.vignetteEnabled;
  81295. },
  81296. /**
  81297. * Sets wether the vignette effect is enabled.
  81298. */
  81299. set: function (value) {
  81300. this.imageProcessingConfiguration.vignetteEnabled = value;
  81301. },
  81302. enumerable: true,
  81303. configurable: true
  81304. });
  81305. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  81306. /**
  81307. * Gets wether the input of the processing is in Gamma or Linear Space.
  81308. */
  81309. get: function () {
  81310. return this._fromLinearSpace;
  81311. },
  81312. /**
  81313. * Sets wether the input of the processing is in Gamma or Linear Space.
  81314. */
  81315. set: function (value) {
  81316. if (this._fromLinearSpace === value) {
  81317. return;
  81318. }
  81319. this._fromLinearSpace = value;
  81320. this._updateParameters();
  81321. },
  81322. enumerable: true,
  81323. configurable: true
  81324. });
  81325. ImageProcessingPostProcess.prototype.getClassName = function () {
  81326. return "ImageProcessingPostProcess";
  81327. };
  81328. ImageProcessingPostProcess.prototype._updateParameters = function () {
  81329. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  81330. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  81331. var defines = "";
  81332. for (var define in this._defines) {
  81333. if (this._defines[define]) {
  81334. defines += "#define " + define + ";\r\n";
  81335. }
  81336. }
  81337. var samplers = ["textureSampler"];
  81338. var uniforms = ["scale"];
  81339. if (BABYLON.ImageProcessingConfiguration) {
  81340. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  81341. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  81342. }
  81343. this.updateEffect(defines, uniforms, samplers);
  81344. };
  81345. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  81346. _super.prototype.dispose.call(this, camera);
  81347. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81348. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81349. }
  81350. if (this._imageProcessingConfiguration) {
  81351. this.imageProcessingConfiguration.applyByPostProcess = false;
  81352. }
  81353. };
  81354. __decorate([
  81355. BABYLON.serialize()
  81356. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  81357. return ImageProcessingPostProcess;
  81358. }(BABYLON.PostProcess));
  81359. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  81360. })(BABYLON || (BABYLON = {}));
  81361. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  81362. var BABYLON;
  81363. (function (BABYLON) {
  81364. /**
  81365. * Class used to store bone information
  81366. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81367. */
  81368. var Bone = /** @class */ (function (_super) {
  81369. __extends(Bone, _super);
  81370. /**
  81371. * Create a new bone
  81372. * @param name defines the bone name
  81373. * @param skeleton defines the parent skeleton
  81374. * @param parentBone defines the parent (can be null if the bone is the root)
  81375. * @param localMatrix defines the local matrix
  81376. * @param restPose defines the rest pose matrix
  81377. * @param baseMatrix defines the base matrix
  81378. * @param index defines index of the bone in the hiearchy
  81379. */
  81380. function Bone(
  81381. /**
  81382. * defines the bone name
  81383. */
  81384. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  81385. if (parentBone === void 0) { parentBone = null; }
  81386. if (localMatrix === void 0) { localMatrix = null; }
  81387. if (restPose === void 0) { restPose = null; }
  81388. if (baseMatrix === void 0) { baseMatrix = null; }
  81389. if (index === void 0) { index = null; }
  81390. var _this = _super.call(this, name, skeleton.getScene()) || this;
  81391. _this.name = name;
  81392. /**
  81393. * Gets the list of child bones
  81394. */
  81395. _this.children = new Array();
  81396. /** Gets the animations associated with this bone */
  81397. _this.animations = new Array();
  81398. /**
  81399. * @hidden Internal only
  81400. * Set this value to map this bone to a different index in the transform matrices
  81401. * Set this value to -1 to exclude the bone from the transform matrices
  81402. */
  81403. _this._index = null;
  81404. _this._absoluteTransform = new BABYLON.Matrix();
  81405. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  81406. _this._scalingDeterminant = 1;
  81407. _this._worldTransform = new BABYLON.Matrix();
  81408. _this._needToDecompose = true;
  81409. _this._needToCompose = false;
  81410. _this._skeleton = skeleton;
  81411. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  81412. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  81413. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  81414. _this._index = index;
  81415. skeleton.bones.push(_this);
  81416. _this.setParent(parentBone, false);
  81417. if (baseMatrix || localMatrix) {
  81418. _this._updateDifferenceMatrix();
  81419. }
  81420. return _this;
  81421. }
  81422. Object.defineProperty(Bone.prototype, "_matrix", {
  81423. /** @hidden */
  81424. get: function () {
  81425. this._compose();
  81426. return this._localMatrix;
  81427. },
  81428. /** @hidden */
  81429. set: function (value) {
  81430. this._localMatrix.copyFrom(value);
  81431. this._needToDecompose = true;
  81432. },
  81433. enumerable: true,
  81434. configurable: true
  81435. });
  81436. // Members
  81437. /**
  81438. * Gets the parent skeleton
  81439. * @returns a skeleton
  81440. */
  81441. Bone.prototype.getSkeleton = function () {
  81442. return this._skeleton;
  81443. };
  81444. /**
  81445. * Gets parent bone
  81446. * @returns a bone or null if the bone is the root of the bone hierarchy
  81447. */
  81448. Bone.prototype.getParent = function () {
  81449. return this._parent;
  81450. };
  81451. /**
  81452. * Sets the parent bone
  81453. * @param parent defines the parent (can be null if the bone is the root)
  81454. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81455. */
  81456. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  81457. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81458. if (this._parent === parent) {
  81459. return;
  81460. }
  81461. if (this._parent) {
  81462. var index = this._parent.children.indexOf(this);
  81463. if (index !== -1) {
  81464. this._parent.children.splice(index, 1);
  81465. }
  81466. }
  81467. this._parent = parent;
  81468. if (this._parent) {
  81469. this._parent.children.push(this);
  81470. }
  81471. if (updateDifferenceMatrix) {
  81472. this._updateDifferenceMatrix();
  81473. }
  81474. this.markAsDirty();
  81475. };
  81476. /**
  81477. * Gets the local matrix
  81478. * @returns a matrix
  81479. */
  81480. Bone.prototype.getLocalMatrix = function () {
  81481. this._compose();
  81482. return this._localMatrix;
  81483. };
  81484. /**
  81485. * Gets the base matrix (initial matrix which remains unchanged)
  81486. * @returns a matrix
  81487. */
  81488. Bone.prototype.getBaseMatrix = function () {
  81489. return this._baseMatrix;
  81490. };
  81491. /**
  81492. * Gets the rest pose matrix
  81493. * @returns a matrix
  81494. */
  81495. Bone.prototype.getRestPose = function () {
  81496. return this._restPose;
  81497. };
  81498. /**
  81499. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  81500. */
  81501. Bone.prototype.getWorldMatrix = function () {
  81502. return this._worldTransform;
  81503. };
  81504. /**
  81505. * Sets the local matrix to rest pose matrix
  81506. */
  81507. Bone.prototype.returnToRest = function () {
  81508. this.updateMatrix(this._restPose.clone());
  81509. };
  81510. /**
  81511. * Gets the inverse of the absolute transform matrix.
  81512. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  81513. * @returns a matrix
  81514. */
  81515. Bone.prototype.getInvertedAbsoluteTransform = function () {
  81516. return this._invertedAbsoluteTransform;
  81517. };
  81518. /**
  81519. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  81520. * @returns a matrix
  81521. */
  81522. Bone.prototype.getAbsoluteTransform = function () {
  81523. return this._absoluteTransform;
  81524. };
  81525. Object.defineProperty(Bone.prototype, "position", {
  81526. // Properties (matches AbstractMesh properties)
  81527. /** Gets or sets current position (in local space) */
  81528. get: function () {
  81529. this._decompose();
  81530. return this._localPosition;
  81531. },
  81532. set: function (newPosition) {
  81533. this._decompose();
  81534. this._localPosition.copyFrom(newPosition);
  81535. this._markAsDirtyAndCompose();
  81536. },
  81537. enumerable: true,
  81538. configurable: true
  81539. });
  81540. Object.defineProperty(Bone.prototype, "rotation", {
  81541. /** Gets or sets current rotation (in local space) */
  81542. get: function () {
  81543. return this.getRotation();
  81544. },
  81545. set: function (newRotation) {
  81546. this.setRotation(newRotation);
  81547. },
  81548. enumerable: true,
  81549. configurable: true
  81550. });
  81551. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  81552. /** Gets or sets current rotation quaternion (in local space) */
  81553. get: function () {
  81554. this._decompose();
  81555. return this._localRotation;
  81556. },
  81557. set: function (newRotation) {
  81558. this.setRotationQuaternion(newRotation);
  81559. },
  81560. enumerable: true,
  81561. configurable: true
  81562. });
  81563. Object.defineProperty(Bone.prototype, "scaling", {
  81564. /** Gets or sets current scaling (in local space) */
  81565. get: function () {
  81566. return this.getScale();
  81567. },
  81568. set: function (newScaling) {
  81569. this.setScale(newScaling);
  81570. },
  81571. enumerable: true,
  81572. configurable: true
  81573. });
  81574. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  81575. /**
  81576. * Gets the animation properties override
  81577. */
  81578. get: function () {
  81579. return this._skeleton.animationPropertiesOverride;
  81580. },
  81581. enumerable: true,
  81582. configurable: true
  81583. });
  81584. // Methods
  81585. Bone.prototype._decompose = function () {
  81586. if (!this._needToDecompose) {
  81587. return;
  81588. }
  81589. this._needToDecompose = false;
  81590. if (!this._localScaling) {
  81591. this._localScaling = BABYLON.Vector3.Zero();
  81592. this._localRotation = BABYLON.Quaternion.Zero();
  81593. this._localPosition = BABYLON.Vector3.Zero();
  81594. }
  81595. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  81596. };
  81597. Bone.prototype._compose = function () {
  81598. if (!this._needToCompose) {
  81599. return;
  81600. }
  81601. this._needToCompose = false;
  81602. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  81603. };
  81604. /**
  81605. * Update the base and local matrices
  81606. * @param matrix defines the new base or local matrix
  81607. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81608. * @param updateLocalMatrix defines if the local matrix should be updated
  81609. */
  81610. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  81611. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81612. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  81613. this._baseMatrix.copyFrom(matrix);
  81614. if (updateDifferenceMatrix) {
  81615. this._updateDifferenceMatrix();
  81616. }
  81617. if (updateLocalMatrix) {
  81618. this._localMatrix.copyFrom(matrix);
  81619. this._markAsDirtyAndDecompose();
  81620. }
  81621. else {
  81622. this.markAsDirty();
  81623. }
  81624. };
  81625. /** @hidden */
  81626. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  81627. if (updateChildren === void 0) { updateChildren = true; }
  81628. if (!rootMatrix) {
  81629. rootMatrix = this._baseMatrix;
  81630. }
  81631. if (this._parent) {
  81632. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81633. }
  81634. else {
  81635. this._absoluteTransform.copyFrom(rootMatrix);
  81636. }
  81637. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  81638. if (updateChildren) {
  81639. for (var index = 0; index < this.children.length; index++) {
  81640. this.children[index]._updateDifferenceMatrix();
  81641. }
  81642. }
  81643. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  81644. };
  81645. /**
  81646. * Flag the bone as dirty (Forcing it to update everything)
  81647. */
  81648. Bone.prototype.markAsDirty = function () {
  81649. this._currentRenderId++;
  81650. this._childRenderId++;
  81651. this._skeleton._markAsDirty();
  81652. };
  81653. Bone.prototype._markAsDirtyAndCompose = function () {
  81654. this.markAsDirty();
  81655. this._needToCompose = true;
  81656. };
  81657. Bone.prototype._markAsDirtyAndDecompose = function () {
  81658. this.markAsDirty();
  81659. this._needToDecompose = true;
  81660. };
  81661. /**
  81662. * Copy an animation range from another bone
  81663. * @param source defines the source bone
  81664. * @param rangeName defines the range name to copy
  81665. * @param frameOffset defines the frame offset
  81666. * @param rescaleAsRequired defines if rescaling must be applied if required
  81667. * @param skelDimensionsRatio defines the scaling ratio
  81668. * @returns true if operation was successful
  81669. */
  81670. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  81671. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81672. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  81673. // all animation may be coming from a library skeleton, so may need to create animation
  81674. if (this.animations.length === 0) {
  81675. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  81676. this.animations[0].setKeys([]);
  81677. }
  81678. // get animation info / verify there is such a range from the source bone
  81679. var sourceRange = source.animations[0].getRange(rangeName);
  81680. if (!sourceRange) {
  81681. return false;
  81682. }
  81683. var from = sourceRange.from;
  81684. var to = sourceRange.to;
  81685. var sourceKeys = source.animations[0].getKeys();
  81686. // rescaling prep
  81687. var sourceBoneLength = source.length;
  81688. var sourceParent = source.getParent();
  81689. var parent = this.getParent();
  81690. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  81691. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  81692. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  81693. var destKeys = this.animations[0].getKeys();
  81694. // loop vars declaration
  81695. var orig;
  81696. var origTranslation;
  81697. var mat;
  81698. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  81699. orig = sourceKeys[key];
  81700. if (orig.frame >= from && orig.frame <= to) {
  81701. if (rescaleAsRequired) {
  81702. mat = orig.value.clone();
  81703. // scale based on parent ratio, when bone has parent
  81704. if (parentScalingReqd) {
  81705. origTranslation = mat.getTranslation();
  81706. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  81707. // scale based on skeleton dimension ratio when root bone, and value is passed
  81708. }
  81709. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  81710. origTranslation = mat.getTranslation();
  81711. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  81712. // use original when root bone, and no data for skelDimensionsRatio
  81713. }
  81714. else {
  81715. mat = orig.value;
  81716. }
  81717. }
  81718. else {
  81719. mat = orig.value;
  81720. }
  81721. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  81722. }
  81723. }
  81724. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  81725. return true;
  81726. };
  81727. /**
  81728. * Translate the bone in local or world space
  81729. * @param vec The amount to translate the bone
  81730. * @param space The space that the translation is in
  81731. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81732. */
  81733. Bone.prototype.translate = function (vec, space, mesh) {
  81734. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81735. var lm = this.getLocalMatrix();
  81736. if (space == BABYLON.Space.LOCAL) {
  81737. lm.m[12] += vec.x;
  81738. lm.m[13] += vec.y;
  81739. lm.m[14] += vec.z;
  81740. }
  81741. else {
  81742. var wm = null;
  81743. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81744. if (mesh) {
  81745. wm = mesh.getWorldMatrix();
  81746. }
  81747. this._skeleton.computeAbsoluteTransforms();
  81748. var tmat = Bone._tmpMats[0];
  81749. var tvec = Bone._tmpVecs[0];
  81750. if (this._parent) {
  81751. if (mesh && wm) {
  81752. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81753. tmat.multiplyToRef(wm, tmat);
  81754. }
  81755. else {
  81756. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81757. }
  81758. }
  81759. tmat.m[12] = 0;
  81760. tmat.m[13] = 0;
  81761. tmat.m[14] = 0;
  81762. tmat.invert();
  81763. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  81764. lm.m[12] += tvec.x;
  81765. lm.m[13] += tvec.y;
  81766. lm.m[14] += tvec.z;
  81767. }
  81768. this._markAsDirtyAndDecompose();
  81769. };
  81770. /**
  81771. * Set the postion of the bone in local or world space
  81772. * @param position The position to set the bone
  81773. * @param space The space that the position is in
  81774. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81775. */
  81776. Bone.prototype.setPosition = function (position, space, mesh) {
  81777. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81778. var lm = this.getLocalMatrix();
  81779. if (space == BABYLON.Space.LOCAL) {
  81780. lm.m[12] = position.x;
  81781. lm.m[13] = position.y;
  81782. lm.m[14] = position.z;
  81783. }
  81784. else {
  81785. var wm = null;
  81786. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81787. if (mesh) {
  81788. wm = mesh.getWorldMatrix();
  81789. }
  81790. this._skeleton.computeAbsoluteTransforms();
  81791. var tmat = Bone._tmpMats[0];
  81792. var vec = Bone._tmpVecs[0];
  81793. if (this._parent) {
  81794. if (mesh && wm) {
  81795. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81796. tmat.multiplyToRef(wm, tmat);
  81797. }
  81798. else {
  81799. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81800. }
  81801. }
  81802. tmat.invert();
  81803. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  81804. lm.m[12] = vec.x;
  81805. lm.m[13] = vec.y;
  81806. lm.m[14] = vec.z;
  81807. }
  81808. this._markAsDirtyAndDecompose();
  81809. };
  81810. /**
  81811. * Set the absolute position of the bone (world space)
  81812. * @param position The position to set the bone
  81813. * @param mesh The mesh that this bone is attached to
  81814. */
  81815. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  81816. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  81817. };
  81818. /**
  81819. * Scale the bone on the x, y and z axes (in local space)
  81820. * @param x The amount to scale the bone on the x axis
  81821. * @param y The amount to scale the bone on the y axis
  81822. * @param z The amount to scale the bone on the z axis
  81823. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  81824. */
  81825. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  81826. if (scaleChildren === void 0) { scaleChildren = false; }
  81827. var locMat = this.getLocalMatrix();
  81828. // Apply new scaling on top of current local matrix
  81829. var scaleMat = Bone._tmpMats[0];
  81830. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  81831. scaleMat.multiplyToRef(locMat, locMat);
  81832. // Invert scaling matrix and apply the inverse to all children
  81833. scaleMat.invert();
  81834. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  81835. var child = _a[_i];
  81836. var cm = child.getLocalMatrix();
  81837. cm.multiplyToRef(scaleMat, cm);
  81838. cm.m[12] *= x;
  81839. cm.m[13] *= y;
  81840. cm.m[14] *= z;
  81841. child._markAsDirtyAndDecompose();
  81842. }
  81843. this._markAsDirtyAndDecompose();
  81844. if (scaleChildren) {
  81845. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  81846. var child = _c[_b];
  81847. child.scale(x, y, z, scaleChildren);
  81848. }
  81849. }
  81850. };
  81851. /**
  81852. * Set the bone scaling in local space
  81853. * @param scale defines the scaling vector
  81854. */
  81855. Bone.prototype.setScale = function (scale) {
  81856. this._decompose();
  81857. this._localScaling.copyFrom(scale);
  81858. this._markAsDirtyAndCompose();
  81859. };
  81860. /**
  81861. * Gets the current scaling in local space
  81862. * @returns the current scaling vector
  81863. */
  81864. Bone.prototype.getScale = function () {
  81865. this._decompose();
  81866. return this._localScaling;
  81867. };
  81868. /**
  81869. * Gets the current scaling in local space and stores it in a target vector
  81870. * @param result defines the target vector
  81871. */
  81872. Bone.prototype.getScaleToRef = function (result) {
  81873. this._decompose();
  81874. result.copyFrom(this._localScaling);
  81875. };
  81876. /**
  81877. * Set the yaw, pitch, and roll of the bone in local or world space
  81878. * @param yaw The rotation of the bone on the y axis
  81879. * @param pitch The rotation of the bone on the x axis
  81880. * @param roll The rotation of the bone on the z axis
  81881. * @param space The space that the axes of rotation are in
  81882. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81883. */
  81884. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  81885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81886. if (space === BABYLON.Space.LOCAL) {
  81887. var quat = Bone._tmpQuat;
  81888. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  81889. this.setRotationQuaternion(quat, space, mesh);
  81890. return;
  81891. }
  81892. var rotMatInv = Bone._tmpMats[0];
  81893. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81894. return;
  81895. }
  81896. var rotMat = Bone._tmpMats[1];
  81897. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  81898. rotMatInv.multiplyToRef(rotMat, rotMat);
  81899. this._rotateWithMatrix(rotMat, space, mesh);
  81900. };
  81901. /**
  81902. * Add a rotation to the bone on an axis in local or world space
  81903. * @param axis The axis to rotate the bone on
  81904. * @param amount The amount to rotate the bone
  81905. * @param space The space that the axis is in
  81906. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81907. */
  81908. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  81909. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81910. var rmat = Bone._tmpMats[0];
  81911. rmat.m[12] = 0;
  81912. rmat.m[13] = 0;
  81913. rmat.m[14] = 0;
  81914. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  81915. this._rotateWithMatrix(rmat, space, mesh);
  81916. };
  81917. /**
  81918. * Set the rotation of the bone to a particular axis angle in local or world space
  81919. * @param axis The axis to rotate the bone on
  81920. * @param angle The angle that the bone should be rotated to
  81921. * @param space The space that the axis is in
  81922. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81923. */
  81924. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  81925. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81926. if (space === BABYLON.Space.LOCAL) {
  81927. var quat = Bone._tmpQuat;
  81928. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  81929. this.setRotationQuaternion(quat, space, mesh);
  81930. return;
  81931. }
  81932. var rotMatInv = Bone._tmpMats[0];
  81933. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81934. return;
  81935. }
  81936. var rotMat = Bone._tmpMats[1];
  81937. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  81938. rotMatInv.multiplyToRef(rotMat, rotMat);
  81939. this._rotateWithMatrix(rotMat, space, mesh);
  81940. };
  81941. /**
  81942. * Set the euler rotation of the bone in local of world space
  81943. * @param rotation The euler rotation that the bone should be set to
  81944. * @param space The space that the rotation is in
  81945. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81946. */
  81947. Bone.prototype.setRotation = function (rotation, space, mesh) {
  81948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81949. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  81950. };
  81951. /**
  81952. * Set the quaternion rotation of the bone in local of world space
  81953. * @param quat The quaternion rotation that the bone should be set to
  81954. * @param space The space that the rotation is in
  81955. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81956. */
  81957. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  81958. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81959. if (space === BABYLON.Space.LOCAL) {
  81960. this._decompose();
  81961. this._localRotation.copyFrom(quat);
  81962. this._markAsDirtyAndCompose();
  81963. return;
  81964. }
  81965. var rotMatInv = Bone._tmpMats[0];
  81966. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81967. return;
  81968. }
  81969. var rotMat = Bone._tmpMats[1];
  81970. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  81971. rotMatInv.multiplyToRef(rotMat, rotMat);
  81972. this._rotateWithMatrix(rotMat, space, mesh);
  81973. };
  81974. /**
  81975. * Set the rotation matrix of the bone in local of world space
  81976. * @param rotMat The rotation matrix that the bone should be set to
  81977. * @param space The space that the rotation is in
  81978. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81979. */
  81980. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  81981. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81982. if (space === BABYLON.Space.LOCAL) {
  81983. var quat = Bone._tmpQuat;
  81984. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  81985. this.setRotationQuaternion(quat, space, mesh);
  81986. return;
  81987. }
  81988. var rotMatInv = Bone._tmpMats[0];
  81989. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81990. return;
  81991. }
  81992. var rotMat2 = Bone._tmpMats[1];
  81993. rotMat2.copyFrom(rotMat);
  81994. rotMatInv.multiplyToRef(rotMat, rotMat2);
  81995. this._rotateWithMatrix(rotMat2, space, mesh);
  81996. };
  81997. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  81998. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81999. var lmat = this.getLocalMatrix();
  82000. var lx = lmat.m[12];
  82001. var ly = lmat.m[13];
  82002. var lz = lmat.m[14];
  82003. var parent = this.getParent();
  82004. var parentScale = Bone._tmpMats[3];
  82005. var parentScaleInv = Bone._tmpMats[4];
  82006. if (parent && space == BABYLON.Space.WORLD) {
  82007. if (mesh) {
  82008. parentScale.copyFrom(mesh.getWorldMatrix());
  82009. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  82010. }
  82011. else {
  82012. parentScale.copyFrom(parent.getAbsoluteTransform());
  82013. }
  82014. parentScaleInv.copyFrom(parentScale);
  82015. parentScaleInv.invert();
  82016. lmat.multiplyToRef(parentScale, lmat);
  82017. lmat.multiplyToRef(rmat, lmat);
  82018. lmat.multiplyToRef(parentScaleInv, lmat);
  82019. }
  82020. else {
  82021. if (space == BABYLON.Space.WORLD && mesh) {
  82022. parentScale.copyFrom(mesh.getWorldMatrix());
  82023. parentScaleInv.copyFrom(parentScale);
  82024. parentScaleInv.invert();
  82025. lmat.multiplyToRef(parentScale, lmat);
  82026. lmat.multiplyToRef(rmat, lmat);
  82027. lmat.multiplyToRef(parentScaleInv, lmat);
  82028. }
  82029. else {
  82030. lmat.multiplyToRef(rmat, lmat);
  82031. }
  82032. }
  82033. lmat.m[12] = lx;
  82034. lmat.m[13] = ly;
  82035. lmat.m[14] = lz;
  82036. this.computeAbsoluteTransforms();
  82037. this._markAsDirtyAndDecompose();
  82038. };
  82039. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  82040. var scaleMatrix = Bone._tmpMats[2];
  82041. rotMatInv.copyFrom(this.getAbsoluteTransform());
  82042. if (mesh) {
  82043. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  82044. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  82045. }
  82046. rotMatInv.invert();
  82047. if (isNaN(rotMatInv.m[0])) {
  82048. // Matrix failed to invert.
  82049. // This can happen if scale is zero for example.
  82050. return false;
  82051. }
  82052. scaleMatrix.m[0] *= this._scalingDeterminant;
  82053. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  82054. return true;
  82055. };
  82056. /**
  82057. * Get the position of the bone in local or world space
  82058. * @param space The space that the returned position is in
  82059. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82060. * @returns The position of the bone
  82061. */
  82062. Bone.prototype.getPosition = function (space, mesh) {
  82063. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82064. if (mesh === void 0) { mesh = null; }
  82065. var pos = BABYLON.Vector3.Zero();
  82066. this.getPositionToRef(space, mesh, pos);
  82067. return pos;
  82068. };
  82069. /**
  82070. * Copy the position of the bone to a vector3 in local or world space
  82071. * @param space The space that the returned position is in
  82072. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82073. * @param result The vector3 to copy the position to
  82074. */
  82075. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  82076. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82077. if (space == BABYLON.Space.LOCAL) {
  82078. var lm = this.getLocalMatrix();
  82079. result.x = lm.m[12];
  82080. result.y = lm.m[13];
  82081. result.z = lm.m[14];
  82082. }
  82083. else {
  82084. var wm = null;
  82085. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82086. if (mesh) {
  82087. wm = mesh.getWorldMatrix();
  82088. }
  82089. this._skeleton.computeAbsoluteTransforms();
  82090. var tmat = Bone._tmpMats[0];
  82091. if (mesh && wm) {
  82092. tmat.copyFrom(this.getAbsoluteTransform());
  82093. tmat.multiplyToRef(wm, tmat);
  82094. }
  82095. else {
  82096. tmat = this.getAbsoluteTransform();
  82097. }
  82098. result.x = tmat.m[12];
  82099. result.y = tmat.m[13];
  82100. result.z = tmat.m[14];
  82101. }
  82102. };
  82103. /**
  82104. * Get the absolute position of the bone (world space)
  82105. * @param mesh The mesh that this bone is attached to
  82106. * @returns The absolute position of the bone
  82107. */
  82108. Bone.prototype.getAbsolutePosition = function (mesh) {
  82109. if (mesh === void 0) { mesh = null; }
  82110. var pos = BABYLON.Vector3.Zero();
  82111. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  82112. return pos;
  82113. };
  82114. /**
  82115. * Copy the absolute position of the bone (world space) to the result param
  82116. * @param mesh The mesh that this bone is attached to
  82117. * @param result The vector3 to copy the absolute position to
  82118. */
  82119. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  82120. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  82121. };
  82122. /**
  82123. * Compute the absolute transforms of this bone and its children
  82124. */
  82125. Bone.prototype.computeAbsoluteTransforms = function () {
  82126. this._compose();
  82127. if (this._parent) {
  82128. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82129. }
  82130. else {
  82131. this._absoluteTransform.copyFrom(this._localMatrix);
  82132. var poseMatrix = this._skeleton.getPoseMatrix();
  82133. if (poseMatrix) {
  82134. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  82135. }
  82136. }
  82137. var children = this.children;
  82138. var len = children.length;
  82139. for (var i = 0; i < len; i++) {
  82140. children[i].computeAbsoluteTransforms();
  82141. }
  82142. };
  82143. /**
  82144. * Get the world direction from an axis that is in the local space of the bone
  82145. * @param localAxis The local direction that is used to compute the world direction
  82146. * @param mesh The mesh that this bone is attached to
  82147. * @returns The world direction
  82148. */
  82149. Bone.prototype.getDirection = function (localAxis, mesh) {
  82150. if (mesh === void 0) { mesh = null; }
  82151. var result = BABYLON.Vector3.Zero();
  82152. this.getDirectionToRef(localAxis, mesh, result);
  82153. return result;
  82154. };
  82155. /**
  82156. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  82157. * @param localAxis The local direction that is used to compute the world direction
  82158. * @param mesh The mesh that this bone is attached to
  82159. * @param result The vector3 that the world direction will be copied to
  82160. */
  82161. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  82162. if (mesh === void 0) { mesh = null; }
  82163. var wm = null;
  82164. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82165. if (mesh) {
  82166. wm = mesh.getWorldMatrix();
  82167. }
  82168. this._skeleton.computeAbsoluteTransforms();
  82169. var mat = Bone._tmpMats[0];
  82170. mat.copyFrom(this.getAbsoluteTransform());
  82171. if (mesh && wm) {
  82172. mat.multiplyToRef(wm, mat);
  82173. }
  82174. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  82175. result.normalize();
  82176. };
  82177. /**
  82178. * Get the euler rotation of the bone in local or world space
  82179. * @param space The space that the rotation should be in
  82180. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82181. * @returns The euler rotation
  82182. */
  82183. Bone.prototype.getRotation = function (space, mesh) {
  82184. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82185. if (mesh === void 0) { mesh = null; }
  82186. var result = BABYLON.Vector3.Zero();
  82187. this.getRotationToRef(space, mesh, result);
  82188. return result;
  82189. };
  82190. /**
  82191. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  82192. * @param space The space that the rotation should be in
  82193. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82194. * @param result The vector3 that the rotation should be copied to
  82195. */
  82196. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  82197. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82198. if (mesh === void 0) { mesh = null; }
  82199. var quat = Bone._tmpQuat;
  82200. this.getRotationQuaternionToRef(space, mesh, quat);
  82201. quat.toEulerAnglesToRef(result);
  82202. };
  82203. /**
  82204. * Get the quaternion rotation of the bone in either local or world space
  82205. * @param space The space that the rotation should be in
  82206. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82207. * @returns The quaternion rotation
  82208. */
  82209. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  82210. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82211. if (mesh === void 0) { mesh = null; }
  82212. var result = BABYLON.Quaternion.Identity();
  82213. this.getRotationQuaternionToRef(space, mesh, result);
  82214. return result;
  82215. };
  82216. /**
  82217. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  82218. * @param space The space that the rotation should be in
  82219. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82220. * @param result The quaternion that the rotation should be copied to
  82221. */
  82222. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  82223. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82224. if (mesh === void 0) { mesh = null; }
  82225. if (space == BABYLON.Space.LOCAL) {
  82226. this._decompose();
  82227. result.copyFrom(this._localRotation);
  82228. }
  82229. else {
  82230. var mat = Bone._tmpMats[0];
  82231. var amat = this.getAbsoluteTransform();
  82232. if (mesh) {
  82233. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  82234. }
  82235. else {
  82236. mat.copyFrom(amat);
  82237. }
  82238. mat.m[0] *= this._scalingDeterminant;
  82239. mat.m[1] *= this._scalingDeterminant;
  82240. mat.m[2] *= this._scalingDeterminant;
  82241. mat.decompose(undefined, result, undefined);
  82242. }
  82243. };
  82244. /**
  82245. * Get the rotation matrix of the bone in local or world space
  82246. * @param space The space that the rotation should be in
  82247. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82248. * @returns The rotation matrix
  82249. */
  82250. Bone.prototype.getRotationMatrix = function (space, mesh) {
  82251. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82252. var result = BABYLON.Matrix.Identity();
  82253. this.getRotationMatrixToRef(space, mesh, result);
  82254. return result;
  82255. };
  82256. /**
  82257. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  82258. * @param space The space that the rotation should be in
  82259. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82260. * @param result The quaternion that the rotation should be copied to
  82261. */
  82262. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  82263. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82264. if (space == BABYLON.Space.LOCAL) {
  82265. this.getLocalMatrix().getRotationMatrixToRef(result);
  82266. }
  82267. else {
  82268. var mat = Bone._tmpMats[0];
  82269. var amat = this.getAbsoluteTransform();
  82270. if (mesh) {
  82271. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  82272. }
  82273. else {
  82274. mat.copyFrom(amat);
  82275. }
  82276. mat.m[0] *= this._scalingDeterminant;
  82277. mat.m[1] *= this._scalingDeterminant;
  82278. mat.m[2] *= this._scalingDeterminant;
  82279. mat.getRotationMatrixToRef(result);
  82280. }
  82281. };
  82282. /**
  82283. * Get the world position of a point that is in the local space of the bone
  82284. * @param position The local position
  82285. * @param mesh The mesh that this bone is attached to
  82286. * @returns The world position
  82287. */
  82288. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  82289. if (mesh === void 0) { mesh = null; }
  82290. var result = BABYLON.Vector3.Zero();
  82291. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  82292. return result;
  82293. };
  82294. /**
  82295. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  82296. * @param position The local position
  82297. * @param mesh The mesh that this bone is attached to
  82298. * @param result The vector3 that the world position should be copied to
  82299. */
  82300. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  82301. if (mesh === void 0) { mesh = null; }
  82302. var wm = null;
  82303. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82304. if (mesh) {
  82305. wm = mesh.getWorldMatrix();
  82306. }
  82307. this._skeleton.computeAbsoluteTransforms();
  82308. var tmat = Bone._tmpMats[0];
  82309. if (mesh && wm) {
  82310. tmat.copyFrom(this.getAbsoluteTransform());
  82311. tmat.multiplyToRef(wm, tmat);
  82312. }
  82313. else {
  82314. tmat = this.getAbsoluteTransform();
  82315. }
  82316. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  82317. };
  82318. /**
  82319. * Get the local position of a point that is in world space
  82320. * @param position The world position
  82321. * @param mesh The mesh that this bone is attached to
  82322. * @returns The local position
  82323. */
  82324. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  82325. if (mesh === void 0) { mesh = null; }
  82326. var result = BABYLON.Vector3.Zero();
  82327. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  82328. return result;
  82329. };
  82330. /**
  82331. * Get the local position of a point that is in world space and copy it to the result param
  82332. * @param position The world position
  82333. * @param mesh The mesh that this bone is attached to
  82334. * @param result The vector3 that the local position should be copied to
  82335. */
  82336. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  82337. if (mesh === void 0) { mesh = null; }
  82338. var wm = null;
  82339. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82340. if (mesh) {
  82341. wm = mesh.getWorldMatrix();
  82342. }
  82343. this._skeleton.computeAbsoluteTransforms();
  82344. var tmat = Bone._tmpMats[0];
  82345. tmat.copyFrom(this.getAbsoluteTransform());
  82346. if (mesh && wm) {
  82347. tmat.multiplyToRef(wm, tmat);
  82348. }
  82349. tmat.invert();
  82350. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  82351. };
  82352. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82353. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  82354. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82355. return Bone;
  82356. }(BABYLON.Node));
  82357. BABYLON.Bone = Bone;
  82358. })(BABYLON || (BABYLON = {}));
  82359. //# sourceMappingURL=babylon.bone.js.map
  82360. var BABYLON;
  82361. (function (BABYLON) {
  82362. /**
  82363. * Class used to apply inverse kinematics to bones
  82364. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  82365. */
  82366. var BoneIKController = /** @class */ (function () {
  82367. /**
  82368. * Creates a new BoneIKController
  82369. * @param mesh defines the mesh to control
  82370. * @param bone defines the bone to control
  82371. * @param options defines options to set up the controller
  82372. */
  82373. function BoneIKController(mesh, bone, options) {
  82374. /**
  82375. * Gets or sets the target position
  82376. */
  82377. this.targetPosition = BABYLON.Vector3.Zero();
  82378. /**
  82379. * Gets or sets the pole target position
  82380. */
  82381. this.poleTargetPosition = BABYLON.Vector3.Zero();
  82382. /**
  82383. * Gets or sets the pole target local offset
  82384. */
  82385. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  82386. /**
  82387. * Gets or sets the pole angle
  82388. */
  82389. this.poleAngle = 0;
  82390. /**
  82391. * 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)
  82392. */
  82393. this.slerpAmount = 1;
  82394. this._bone1Quat = BABYLON.Quaternion.Identity();
  82395. this._bone1Mat = BABYLON.Matrix.Identity();
  82396. this._bone2Ang = Math.PI;
  82397. this._maxAngle = Math.PI;
  82398. this._rightHandedSystem = false;
  82399. this._bendAxis = BABYLON.Vector3.Right();
  82400. this._slerping = false;
  82401. this._adjustRoll = 0;
  82402. this._bone2 = bone;
  82403. this._bone1 = bone.getParent();
  82404. if (!this._bone1) {
  82405. return;
  82406. }
  82407. this.mesh = mesh;
  82408. var bonePos = bone.getPosition();
  82409. if (bone.getAbsoluteTransform().determinant() > 0) {
  82410. this._rightHandedSystem = true;
  82411. this._bendAxis.x = 0;
  82412. this._bendAxis.y = 0;
  82413. this._bendAxis.z = -1;
  82414. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  82415. this._adjustRoll = Math.PI * .5;
  82416. this._bendAxis.z = 1;
  82417. }
  82418. }
  82419. if (this._bone1.length) {
  82420. var boneScale1 = this._bone1.getScale();
  82421. var boneScale2 = this._bone2.getScale();
  82422. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  82423. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  82424. }
  82425. else if (this._bone1.children[0]) {
  82426. mesh.computeWorldMatrix(true);
  82427. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  82428. var pos2 = this._bone2.getAbsolutePosition(mesh);
  82429. var pos3 = this._bone1.getAbsolutePosition(mesh);
  82430. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  82431. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  82432. }
  82433. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  82434. this.maxAngle = Math.PI;
  82435. if (options) {
  82436. if (options.targetMesh) {
  82437. this.targetMesh = options.targetMesh;
  82438. this.targetMesh.computeWorldMatrix(true);
  82439. }
  82440. if (options.poleTargetMesh) {
  82441. this.poleTargetMesh = options.poleTargetMesh;
  82442. this.poleTargetMesh.computeWorldMatrix(true);
  82443. }
  82444. else if (options.poleTargetBone) {
  82445. this.poleTargetBone = options.poleTargetBone;
  82446. }
  82447. else if (this._bone1.getParent()) {
  82448. this.poleTargetBone = this._bone1.getParent();
  82449. }
  82450. if (options.poleTargetLocalOffset) {
  82451. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  82452. }
  82453. if (options.poleAngle) {
  82454. this.poleAngle = options.poleAngle;
  82455. }
  82456. if (options.bendAxis) {
  82457. this._bendAxis.copyFrom(options.bendAxis);
  82458. }
  82459. if (options.maxAngle) {
  82460. this.maxAngle = options.maxAngle;
  82461. }
  82462. if (options.slerpAmount) {
  82463. this.slerpAmount = options.slerpAmount;
  82464. }
  82465. }
  82466. }
  82467. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  82468. /**
  82469. * Gets or sets maximum allowed angle
  82470. */
  82471. get: function () {
  82472. return this._maxAngle;
  82473. },
  82474. set: function (value) {
  82475. this._setMaxAngle(value);
  82476. },
  82477. enumerable: true,
  82478. configurable: true
  82479. });
  82480. BoneIKController.prototype._setMaxAngle = function (ang) {
  82481. if (ang < 0) {
  82482. ang = 0;
  82483. }
  82484. if (ang > Math.PI || ang == undefined) {
  82485. ang = Math.PI;
  82486. }
  82487. this._maxAngle = ang;
  82488. var a = this._bone1Length;
  82489. var b = this._bone2Length;
  82490. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  82491. };
  82492. /**
  82493. * Force the controller to update the bones
  82494. */
  82495. BoneIKController.prototype.update = function () {
  82496. var bone1 = this._bone1;
  82497. if (!bone1) {
  82498. return;
  82499. }
  82500. var target = this.targetPosition;
  82501. var poleTarget = this.poleTargetPosition;
  82502. var mat1 = BoneIKController._tmpMats[0];
  82503. var mat2 = BoneIKController._tmpMats[1];
  82504. if (this.targetMesh) {
  82505. target.copyFrom(this.targetMesh.getAbsolutePosition());
  82506. }
  82507. if (this.poleTargetBone) {
  82508. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  82509. }
  82510. else if (this.poleTargetMesh) {
  82511. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  82512. }
  82513. var bonePos = BoneIKController._tmpVecs[0];
  82514. var zaxis = BoneIKController._tmpVecs[1];
  82515. var xaxis = BoneIKController._tmpVecs[2];
  82516. var yaxis = BoneIKController._tmpVecs[3];
  82517. var upAxis = BoneIKController._tmpVecs[4];
  82518. var _tmpQuat = BoneIKController._tmpQuat;
  82519. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  82520. poleTarget.subtractToRef(bonePos, upAxis);
  82521. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  82522. upAxis.y = 1;
  82523. }
  82524. else {
  82525. upAxis.normalize();
  82526. }
  82527. target.subtractToRef(bonePos, yaxis);
  82528. yaxis.normalize();
  82529. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  82530. zaxis.normalize();
  82531. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  82532. xaxis.normalize();
  82533. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  82534. var a = this._bone1Length;
  82535. var b = this._bone2Length;
  82536. var c = BABYLON.Vector3.Distance(bonePos, target);
  82537. if (this._maxReach > 0) {
  82538. c = Math.min(this._maxReach, c);
  82539. }
  82540. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  82541. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  82542. if (acosa > 1) {
  82543. acosa = 1;
  82544. }
  82545. if (acosb > 1) {
  82546. acosb = 1;
  82547. }
  82548. if (acosa < -1) {
  82549. acosa = -1;
  82550. }
  82551. if (acosb < -1) {
  82552. acosb = -1;
  82553. }
  82554. var angA = Math.acos(acosa);
  82555. var angB = Math.acos(acosb);
  82556. var angC = -angA - angB;
  82557. if (this._rightHandedSystem) {
  82558. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  82559. mat2.multiplyToRef(mat1, mat1);
  82560. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  82561. mat2.multiplyToRef(mat1, mat1);
  82562. }
  82563. else {
  82564. var _tmpVec = BoneIKController._tmpVecs[5];
  82565. _tmpVec.copyFrom(this._bendAxis);
  82566. _tmpVec.x *= -1;
  82567. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  82568. mat2.multiplyToRef(mat1, mat1);
  82569. }
  82570. if (this.poleAngle) {
  82571. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  82572. mat1.multiplyToRef(mat2, mat1);
  82573. }
  82574. if (this._bone1) {
  82575. if (this.slerpAmount < 1) {
  82576. if (!this._slerping) {
  82577. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  82578. }
  82579. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  82580. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  82581. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  82582. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  82583. this._slerping = true;
  82584. }
  82585. else {
  82586. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  82587. this._bone1Mat.copyFrom(mat1);
  82588. this._slerping = false;
  82589. }
  82590. }
  82591. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  82592. this._bone2Ang = angC;
  82593. };
  82594. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82595. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  82596. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82597. return BoneIKController;
  82598. }());
  82599. BABYLON.BoneIKController = BoneIKController;
  82600. })(BABYLON || (BABYLON = {}));
  82601. //# sourceMappingURL=babylon.boneIKController.js.map
  82602. var BABYLON;
  82603. (function (BABYLON) {
  82604. /**
  82605. * Class used to make a bone look toward a point in space
  82606. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  82607. */
  82608. var BoneLookController = /** @class */ (function () {
  82609. /**
  82610. * Create a BoneLookController
  82611. * @param mesh the mesh that the bone belongs to
  82612. * @param bone the bone that will be looking to the target
  82613. * @param target the target Vector3 to look at
  82614. * @param settings optional settings:
  82615. * * maxYaw: the maximum angle the bone will yaw to
  82616. * * minYaw: the minimum angle the bone will yaw to
  82617. * * maxPitch: the maximum angle the bone will pitch to
  82618. * * minPitch: the minimum angle the bone will yaw to
  82619. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  82620. * * upAxis: the up axis of the coordinate system
  82621. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  82622. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  82623. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  82624. * * adjustYaw: used to make an adjustment to the yaw of the bone
  82625. * * adjustPitch: used to make an adjustment to the pitch of the bone
  82626. * * adjustRoll: used to make an adjustment to the roll of the bone
  82627. **/
  82628. function BoneLookController(mesh, bone, target, options) {
  82629. /**
  82630. * The up axis of the coordinate system that is used when the bone is rotated
  82631. */
  82632. this.upAxis = BABYLON.Vector3.Up();
  82633. /**
  82634. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  82635. */
  82636. this.upAxisSpace = BABYLON.Space.LOCAL;
  82637. /**
  82638. * Used to make an adjustment to the yaw of the bone
  82639. */
  82640. this.adjustYaw = 0;
  82641. /**
  82642. * Used to make an adjustment to the pitch of the bone
  82643. */
  82644. this.adjustPitch = 0;
  82645. /**
  82646. * Used to make an adjustment to the roll of the bone
  82647. */
  82648. this.adjustRoll = 0;
  82649. /**
  82650. * 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)
  82651. */
  82652. this.slerpAmount = 1;
  82653. this._boneQuat = BABYLON.Quaternion.Identity();
  82654. this._slerping = false;
  82655. this._firstFrameSkipped = false;
  82656. this._fowardAxis = BABYLON.Vector3.Forward();
  82657. this.mesh = mesh;
  82658. this.bone = bone;
  82659. this.target = target;
  82660. if (options) {
  82661. if (options.adjustYaw) {
  82662. this.adjustYaw = options.adjustYaw;
  82663. }
  82664. if (options.adjustPitch) {
  82665. this.adjustPitch = options.adjustPitch;
  82666. }
  82667. if (options.adjustRoll) {
  82668. this.adjustRoll = options.adjustRoll;
  82669. }
  82670. if (options.maxYaw != null) {
  82671. this.maxYaw = options.maxYaw;
  82672. }
  82673. else {
  82674. this.maxYaw = Math.PI;
  82675. }
  82676. if (options.minYaw != null) {
  82677. this.minYaw = options.minYaw;
  82678. }
  82679. else {
  82680. this.minYaw = -Math.PI;
  82681. }
  82682. if (options.maxPitch != null) {
  82683. this.maxPitch = options.maxPitch;
  82684. }
  82685. else {
  82686. this.maxPitch = Math.PI;
  82687. }
  82688. if (options.minPitch != null) {
  82689. this.minPitch = options.minPitch;
  82690. }
  82691. else {
  82692. this.minPitch = -Math.PI;
  82693. }
  82694. if (options.slerpAmount != null) {
  82695. this.slerpAmount = options.slerpAmount;
  82696. }
  82697. if (options.upAxis != null) {
  82698. this.upAxis = options.upAxis;
  82699. }
  82700. if (options.upAxisSpace != null) {
  82701. this.upAxisSpace = options.upAxisSpace;
  82702. }
  82703. if (options.yawAxis != null || options.pitchAxis != null) {
  82704. var newYawAxis = BABYLON.Axis.Y;
  82705. var newPitchAxis = BABYLON.Axis.X;
  82706. if (options.yawAxis != null) {
  82707. newYawAxis = options.yawAxis.clone();
  82708. newYawAxis.normalize();
  82709. }
  82710. if (options.pitchAxis != null) {
  82711. newPitchAxis = options.pitchAxis.clone();
  82712. newPitchAxis.normalize();
  82713. }
  82714. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  82715. this._transformYawPitch = BABYLON.Matrix.Identity();
  82716. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  82717. this._transformYawPitchInv = this._transformYawPitch.clone();
  82718. this._transformYawPitch.invert();
  82719. }
  82720. }
  82721. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  82722. this.upAxisSpace = BABYLON.Space.LOCAL;
  82723. }
  82724. }
  82725. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  82726. /**
  82727. * Gets or sets the minimum yaw angle that the bone can look to
  82728. */
  82729. get: function () {
  82730. return this._minYaw;
  82731. },
  82732. set: function (value) {
  82733. this._minYaw = value;
  82734. this._minYawSin = Math.sin(value);
  82735. this._minYawCos = Math.cos(value);
  82736. if (this._maxYaw != null) {
  82737. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82738. this._yawRange = this._maxYaw - this._minYaw;
  82739. }
  82740. },
  82741. enumerable: true,
  82742. configurable: true
  82743. });
  82744. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  82745. /**
  82746. * Gets or sets the maximum yaw angle that the bone can look to
  82747. */
  82748. get: function () {
  82749. return this._maxYaw;
  82750. },
  82751. set: function (value) {
  82752. this._maxYaw = value;
  82753. this._maxYawSin = Math.sin(value);
  82754. this._maxYawCos = Math.cos(value);
  82755. if (this._minYaw != null) {
  82756. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82757. this._yawRange = this._maxYaw - this._minYaw;
  82758. }
  82759. },
  82760. enumerable: true,
  82761. configurable: true
  82762. });
  82763. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  82764. /**
  82765. * Gets or sets the minimum pitch angle that the bone can look to
  82766. */
  82767. get: function () {
  82768. return this._minPitch;
  82769. },
  82770. set: function (value) {
  82771. this._minPitch = value;
  82772. this._minPitchTan = Math.tan(value);
  82773. },
  82774. enumerable: true,
  82775. configurable: true
  82776. });
  82777. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  82778. /**
  82779. * Gets or sets the maximum pitch angle that the bone can look to
  82780. */
  82781. get: function () {
  82782. return this._maxPitch;
  82783. },
  82784. set: function (value) {
  82785. this._maxPitch = value;
  82786. this._maxPitchTan = Math.tan(value);
  82787. },
  82788. enumerable: true,
  82789. configurable: true
  82790. });
  82791. /**
  82792. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  82793. */
  82794. BoneLookController.prototype.update = function () {
  82795. //skip the first frame when slerping so that the mesh rotation is correct
  82796. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  82797. this._firstFrameSkipped = true;
  82798. return;
  82799. }
  82800. var bone = this.bone;
  82801. var bonePos = BoneLookController._tmpVecs[0];
  82802. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  82803. var target = this.target;
  82804. var _tmpMat1 = BoneLookController._tmpMats[0];
  82805. var _tmpMat2 = BoneLookController._tmpMats[1];
  82806. var mesh = this.mesh;
  82807. var parentBone = bone.getParent();
  82808. var upAxis = BoneLookController._tmpVecs[1];
  82809. upAxis.copyFrom(this.upAxis);
  82810. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  82811. if (this._transformYawPitch) {
  82812. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  82813. }
  82814. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  82815. }
  82816. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  82817. mesh.getDirectionToRef(upAxis, upAxis);
  82818. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  82819. upAxis.normalize();
  82820. }
  82821. }
  82822. var checkYaw = false;
  82823. var checkPitch = false;
  82824. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  82825. checkYaw = true;
  82826. }
  82827. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  82828. checkPitch = true;
  82829. }
  82830. if (checkYaw || checkPitch) {
  82831. var spaceMat = BoneLookController._tmpMats[2];
  82832. var spaceMatInv = BoneLookController._tmpMats[3];
  82833. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  82834. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  82835. }
  82836. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  82837. spaceMat.copyFrom(mesh.getWorldMatrix());
  82838. }
  82839. else {
  82840. var forwardAxis = BoneLookController._tmpVecs[2];
  82841. forwardAxis.copyFrom(this._fowardAxis);
  82842. if (this._transformYawPitch) {
  82843. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  82844. }
  82845. if (parentBone) {
  82846. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  82847. }
  82848. else {
  82849. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  82850. }
  82851. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  82852. rightAxis.normalize();
  82853. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  82854. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  82855. }
  82856. spaceMat.invertToRef(spaceMatInv);
  82857. var xzlen = null;
  82858. if (checkPitch) {
  82859. var localTarget = BoneLookController._tmpVecs[3];
  82860. target.subtractToRef(bonePos, localTarget);
  82861. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82862. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82863. var pitch = Math.atan2(localTarget.y, xzlen);
  82864. var newPitch = pitch;
  82865. if (pitch > this._maxPitch) {
  82866. localTarget.y = this._maxPitchTan * xzlen;
  82867. newPitch = this._maxPitch;
  82868. }
  82869. else if (pitch < this._minPitch) {
  82870. localTarget.y = this._minPitchTan * xzlen;
  82871. newPitch = this._minPitch;
  82872. }
  82873. if (pitch != newPitch) {
  82874. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82875. localTarget.addInPlace(bonePos);
  82876. target = localTarget;
  82877. }
  82878. }
  82879. if (checkYaw) {
  82880. var localTarget = BoneLookController._tmpVecs[4];
  82881. target.subtractToRef(bonePos, localTarget);
  82882. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82883. var yaw = Math.atan2(localTarget.x, localTarget.z);
  82884. var newYaw = yaw;
  82885. if (yaw > this._maxYaw || yaw < this._minYaw) {
  82886. if (xzlen == null) {
  82887. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82888. }
  82889. if (this._yawRange > Math.PI) {
  82890. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  82891. localTarget.z = this._maxYawCos * xzlen;
  82892. localTarget.x = this._maxYawSin * xzlen;
  82893. newYaw = this._maxYaw;
  82894. }
  82895. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  82896. localTarget.z = this._minYawCos * xzlen;
  82897. localTarget.x = this._minYawSin * xzlen;
  82898. newYaw = this._minYaw;
  82899. }
  82900. }
  82901. else {
  82902. if (yaw > this._maxYaw) {
  82903. localTarget.z = this._maxYawCos * xzlen;
  82904. localTarget.x = this._maxYawSin * xzlen;
  82905. newYaw = this._maxYaw;
  82906. }
  82907. else if (yaw < this._minYaw) {
  82908. localTarget.z = this._minYawCos * xzlen;
  82909. localTarget.x = this._minYawSin * xzlen;
  82910. newYaw = this._minYaw;
  82911. }
  82912. }
  82913. }
  82914. if (this._slerping && this._yawRange > Math.PI) {
  82915. //are we going to be crossing into the min/max region?
  82916. var boneFwd = BoneLookController._tmpVecs[8];
  82917. boneFwd.copyFrom(BABYLON.Axis.Z);
  82918. if (this._transformYawPitch) {
  82919. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  82920. }
  82921. var boneRotMat = BoneLookController._tmpMats[4];
  82922. this._boneQuat.toRotationMatrix(boneRotMat);
  82923. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  82924. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  82925. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  82926. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  82927. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  82928. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  82929. if (angBtwTar > angBtwMidYaw) {
  82930. if (xzlen == null) {
  82931. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82932. }
  82933. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  82934. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  82935. if (angBtwMin < angBtwMax) {
  82936. newYaw = boneYaw + Math.PI * .75;
  82937. localTarget.z = Math.cos(newYaw) * xzlen;
  82938. localTarget.x = Math.sin(newYaw) * xzlen;
  82939. }
  82940. else {
  82941. newYaw = boneYaw - Math.PI * .75;
  82942. localTarget.z = Math.cos(newYaw) * xzlen;
  82943. localTarget.x = Math.sin(newYaw) * xzlen;
  82944. }
  82945. }
  82946. }
  82947. if (yaw != newYaw) {
  82948. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82949. localTarget.addInPlace(bonePos);
  82950. target = localTarget;
  82951. }
  82952. }
  82953. }
  82954. var zaxis = BoneLookController._tmpVecs[5];
  82955. var xaxis = BoneLookController._tmpVecs[6];
  82956. var yaxis = BoneLookController._tmpVecs[7];
  82957. var _tmpQuat = BoneLookController._tmpQuat;
  82958. target.subtractToRef(bonePos, zaxis);
  82959. zaxis.normalize();
  82960. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  82961. xaxis.normalize();
  82962. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  82963. yaxis.normalize();
  82964. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  82965. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  82966. return;
  82967. }
  82968. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  82969. return;
  82970. }
  82971. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  82972. return;
  82973. }
  82974. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  82975. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  82976. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  82977. }
  82978. if (this.slerpAmount < 1) {
  82979. if (!this._slerping) {
  82980. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  82981. }
  82982. if (this._transformYawPitch) {
  82983. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82984. }
  82985. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  82986. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  82987. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  82988. this._slerping = true;
  82989. }
  82990. else {
  82991. if (this._transformYawPitch) {
  82992. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82993. }
  82994. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  82995. this._slerping = false;
  82996. }
  82997. };
  82998. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  82999. var angDiff = ang2 - ang1;
  83000. angDiff %= Math.PI * 2;
  83001. if (angDiff > Math.PI) {
  83002. angDiff -= Math.PI * 2;
  83003. }
  83004. else if (angDiff < -Math.PI) {
  83005. angDiff += Math.PI * 2;
  83006. }
  83007. return angDiff;
  83008. };
  83009. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  83010. ang1 %= (2 * Math.PI);
  83011. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  83012. ang2 %= (2 * Math.PI);
  83013. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  83014. var ab = 0;
  83015. if (ang1 < ang2) {
  83016. ab = ang2 - ang1;
  83017. }
  83018. else {
  83019. ab = ang1 - ang2;
  83020. }
  83021. if (ab > Math.PI) {
  83022. ab = Math.PI * 2 - ab;
  83023. }
  83024. return ab;
  83025. };
  83026. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  83027. ang %= (2 * Math.PI);
  83028. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  83029. ang1 %= (2 * Math.PI);
  83030. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  83031. ang2 %= (2 * Math.PI);
  83032. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  83033. if (ang1 < ang2) {
  83034. if (ang > ang1 && ang < ang2) {
  83035. return true;
  83036. }
  83037. }
  83038. else {
  83039. if (ang > ang2 && ang < ang1) {
  83040. return true;
  83041. }
  83042. }
  83043. return false;
  83044. };
  83045. 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()];
  83046. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  83047. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83048. return BoneLookController;
  83049. }());
  83050. BABYLON.BoneLookController = BoneLookController;
  83051. })(BABYLON || (BABYLON = {}));
  83052. //# sourceMappingURL=babylon.boneLookController.js.map
  83053. var BABYLON;
  83054. (function (BABYLON) {
  83055. /**
  83056. * Class used to handle skinning animations
  83057. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  83058. */
  83059. var Skeleton = /** @class */ (function () {
  83060. /**
  83061. * Creates a new skeleton
  83062. * @param name defines the skeleton name
  83063. * @param id defines the skeleton Id
  83064. * @param scene defines the hosting scene
  83065. */
  83066. function Skeleton(
  83067. /** defines the skeleton name */
  83068. name,
  83069. /** defines the skeleton Id */
  83070. id, scene) {
  83071. this.name = name;
  83072. this.id = id;
  83073. /**
  83074. * Gets the list of child bones
  83075. */
  83076. this.bones = new Array();
  83077. /**
  83078. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  83079. */
  83080. this.needInitialSkinMatrix = false;
  83081. this._isDirty = true;
  83082. this._meshesWithPoseMatrix = new Array();
  83083. this._identity = BABYLON.Matrix.Identity();
  83084. this._ranges = {};
  83085. this._lastAbsoluteTransformsUpdateId = -1;
  83086. /**
  83087. * Specifies if the skeleton should be serialized
  83088. */
  83089. this.doNotSerialize = false;
  83090. this._animationPropertiesOverride = null;
  83091. // Events
  83092. /**
  83093. * An observable triggered before computing the skeleton's matrices
  83094. */
  83095. this.onBeforeComputeObservable = new BABYLON.Observable();
  83096. this.bones = [];
  83097. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83098. scene.skeletons.push(this);
  83099. //make sure it will recalculate the matrix next time prepare is called.
  83100. this._isDirty = true;
  83101. }
  83102. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  83103. /**
  83104. * Gets or sets the animation properties override
  83105. */
  83106. get: function () {
  83107. if (!this._animationPropertiesOverride) {
  83108. return this._scene.animationPropertiesOverride;
  83109. }
  83110. return this._animationPropertiesOverride;
  83111. },
  83112. set: function (value) {
  83113. this._animationPropertiesOverride = value;
  83114. },
  83115. enumerable: true,
  83116. configurable: true
  83117. });
  83118. // Members
  83119. /**
  83120. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  83121. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  83122. * @returns a Float32Array containing matrices data
  83123. */
  83124. Skeleton.prototype.getTransformMatrices = function (mesh) {
  83125. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  83126. return mesh._bonesTransformMatrices;
  83127. }
  83128. if (!this._transformMatrices) {
  83129. this.prepare();
  83130. }
  83131. return this._transformMatrices;
  83132. };
  83133. /**
  83134. * Gets the current hosting scene
  83135. * @returns a scene object
  83136. */
  83137. Skeleton.prototype.getScene = function () {
  83138. return this._scene;
  83139. };
  83140. // Methods
  83141. /**
  83142. * Gets a string representing the current skeleton data
  83143. * @param fullDetails defines a boolean indicating if we want a verbose version
  83144. * @returns a string representing the current skeleton data
  83145. */
  83146. Skeleton.prototype.toString = function (fullDetails) {
  83147. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  83148. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  83149. if (fullDetails) {
  83150. ret += ", Ranges: {";
  83151. var first = true;
  83152. for (var name_1 in this._ranges) {
  83153. if (first) {
  83154. ret += ", ";
  83155. first = false;
  83156. }
  83157. ret += name_1;
  83158. }
  83159. ret += "}";
  83160. }
  83161. return ret;
  83162. };
  83163. /**
  83164. * Get bone's index searching by name
  83165. * @param name defines bone's name to search for
  83166. * @return the indice of the bone. Returns -1 if not found
  83167. */
  83168. Skeleton.prototype.getBoneIndexByName = function (name) {
  83169. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  83170. if (this.bones[boneIndex].name === name) {
  83171. return boneIndex;
  83172. }
  83173. }
  83174. return -1;
  83175. };
  83176. /**
  83177. * Creater a new animation range
  83178. * @param name defines the name of the range
  83179. * @param from defines the start key
  83180. * @param to defines the end key
  83181. */
  83182. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  83183. // check name not already in use
  83184. if (!this._ranges[name]) {
  83185. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  83186. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83187. if (this.bones[i].animations[0]) {
  83188. this.bones[i].animations[0].createRange(name, from, to);
  83189. }
  83190. }
  83191. }
  83192. };
  83193. /**
  83194. * Delete a specific animation range
  83195. * @param name defines the name of the range
  83196. * @param deleteFrames defines if frames must be removed as well
  83197. */
  83198. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  83199. if (deleteFrames === void 0) { deleteFrames = true; }
  83200. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83201. if (this.bones[i].animations[0]) {
  83202. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  83203. }
  83204. }
  83205. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  83206. };
  83207. /**
  83208. * Gets a specific animation range
  83209. * @param name defines the name of the range to look for
  83210. * @returns the requested animation range or null if not found
  83211. */
  83212. Skeleton.prototype.getAnimationRange = function (name) {
  83213. return this._ranges[name];
  83214. };
  83215. /**
  83216. * Gets the list of all animation ranges defined on this skeleton
  83217. * @returns an array
  83218. */
  83219. Skeleton.prototype.getAnimationRanges = function () {
  83220. var animationRanges = [];
  83221. var name;
  83222. var i = 0;
  83223. for (name in this._ranges) {
  83224. animationRanges[i] = this._ranges[name];
  83225. i++;
  83226. }
  83227. return animationRanges;
  83228. };
  83229. /**
  83230. * Copy animation range from a source skeleton.
  83231. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  83232. * @param source defines the source skeleton
  83233. * @param name defines the name of the range to copy
  83234. * @param rescaleAsRequired defines if rescaling must be applied if required
  83235. * @returns true if operation was successful
  83236. */
  83237. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  83238. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83239. if (this._ranges[name] || !source.getAnimationRange(name)) {
  83240. return false;
  83241. }
  83242. var ret = true;
  83243. var frameOffset = this._getHighestAnimationFrame() + 1;
  83244. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  83245. var boneDict = {};
  83246. var sourceBones = source.bones;
  83247. var nBones;
  83248. var i;
  83249. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  83250. boneDict[sourceBones[i].name] = sourceBones[i];
  83251. }
  83252. if (this.bones.length !== sourceBones.length) {
  83253. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  83254. ret = false;
  83255. }
  83256. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  83257. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  83258. var boneName = this.bones[i].name;
  83259. var sourceBone = boneDict[boneName];
  83260. if (sourceBone) {
  83261. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  83262. }
  83263. else {
  83264. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  83265. ret = false;
  83266. }
  83267. }
  83268. // do not call createAnimationRange(), since it also is done to bones, which was already done
  83269. var range = source.getAnimationRange(name);
  83270. if (range) {
  83271. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  83272. }
  83273. return ret;
  83274. };
  83275. /**
  83276. * Forces the skeleton to go to rest pose
  83277. */
  83278. Skeleton.prototype.returnToRest = function () {
  83279. for (var index = 0; index < this.bones.length; index++) {
  83280. this.bones[index].returnToRest();
  83281. }
  83282. };
  83283. Skeleton.prototype._getHighestAnimationFrame = function () {
  83284. var ret = 0;
  83285. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83286. if (this.bones[i].animations[0]) {
  83287. var highest = this.bones[i].animations[0].getHighestFrame();
  83288. if (ret < highest) {
  83289. ret = highest;
  83290. }
  83291. }
  83292. }
  83293. return ret;
  83294. };
  83295. /**
  83296. * Begin a specific animation range
  83297. * @param name defines the name of the range to start
  83298. * @param loop defines if looping must be turned on (false by default)
  83299. * @param speedRatio defines the speed ratio to apply (1 by default)
  83300. * @param onAnimationEnd defines a callback which will be called when animation will end
  83301. * @returns a new animatable
  83302. */
  83303. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  83304. var range = this.getAnimationRange(name);
  83305. if (!range) {
  83306. return null;
  83307. }
  83308. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  83309. };
  83310. /** @hidden */
  83311. Skeleton.prototype._markAsDirty = function () {
  83312. this._isDirty = true;
  83313. };
  83314. /** @hidden */
  83315. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  83316. this._meshesWithPoseMatrix.push(mesh);
  83317. };
  83318. /** @hidden */
  83319. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  83320. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  83321. if (index > -1) {
  83322. this._meshesWithPoseMatrix.splice(index, 1);
  83323. }
  83324. };
  83325. /** @hidden */
  83326. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  83327. this.onBeforeComputeObservable.notifyObservers(this);
  83328. for (var index = 0; index < this.bones.length; index++) {
  83329. var bone = this.bones[index];
  83330. var parentBone = bone.getParent();
  83331. if (parentBone) {
  83332. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  83333. }
  83334. else {
  83335. if (initialSkinMatrix) {
  83336. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  83337. }
  83338. else {
  83339. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  83340. }
  83341. }
  83342. if (bone._index !== -1) {
  83343. var mappedIndex = bone._index === null ? index : bone._index;
  83344. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  83345. }
  83346. }
  83347. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  83348. };
  83349. /**
  83350. * Build all resources required to render a skeleton
  83351. */
  83352. Skeleton.prototype.prepare = function () {
  83353. if (!this._isDirty) {
  83354. return;
  83355. }
  83356. if (this.needInitialSkinMatrix) {
  83357. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  83358. var mesh = this._meshesWithPoseMatrix[index];
  83359. var poseMatrix = mesh.getPoseMatrix();
  83360. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  83361. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  83362. }
  83363. if (this._synchronizedWithMesh !== mesh) {
  83364. this._synchronizedWithMesh = mesh;
  83365. // Prepare bones
  83366. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  83367. var bone = this.bones[boneIndex];
  83368. if (!bone.getParent()) {
  83369. var matrix = bone.getBaseMatrix();
  83370. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  83371. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  83372. }
  83373. }
  83374. }
  83375. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  83376. }
  83377. }
  83378. else {
  83379. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  83380. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  83381. }
  83382. this._computeTransformMatrices(this._transformMatrices, null);
  83383. }
  83384. this._isDirty = false;
  83385. this._scene._activeBones.addCount(this.bones.length, false);
  83386. };
  83387. /**
  83388. * Gets the list of animatables currently running for this skeleton
  83389. * @returns an array of animatables
  83390. */
  83391. Skeleton.prototype.getAnimatables = function () {
  83392. if (!this._animatables || this._animatables.length !== this.bones.length) {
  83393. this._animatables = [];
  83394. for (var index = 0; index < this.bones.length; index++) {
  83395. this._animatables.push(this.bones[index]);
  83396. }
  83397. }
  83398. return this._animatables;
  83399. };
  83400. /**
  83401. * Clone the current skeleton
  83402. * @param name defines the name of the new skeleton
  83403. * @param id defines the id of the enw skeleton
  83404. * @returns the new skeleton
  83405. */
  83406. Skeleton.prototype.clone = function (name, id) {
  83407. var result = new Skeleton(name, id || name, this._scene);
  83408. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  83409. for (var index = 0; index < this.bones.length; index++) {
  83410. var source = this.bones[index];
  83411. var parentBone = null;
  83412. var parent_1 = source.getParent();
  83413. if (parent_1) {
  83414. var parentIndex = this.bones.indexOf(parent_1);
  83415. parentBone = result.bones[parentIndex];
  83416. }
  83417. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  83418. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  83419. }
  83420. if (this._ranges) {
  83421. result._ranges = {};
  83422. for (var rangeName in this._ranges) {
  83423. var range = this._ranges[rangeName];
  83424. if (range) {
  83425. result._ranges[rangeName] = range.clone();
  83426. }
  83427. }
  83428. }
  83429. this._isDirty = true;
  83430. return result;
  83431. };
  83432. /**
  83433. * Enable animation blending for this skeleton
  83434. * @param blendingSpeed defines the blending speed to apply
  83435. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  83436. */
  83437. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  83438. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  83439. this.bones.forEach(function (bone) {
  83440. bone.animations.forEach(function (animation) {
  83441. animation.enableBlending = true;
  83442. animation.blendingSpeed = blendingSpeed;
  83443. });
  83444. });
  83445. };
  83446. /**
  83447. * Releases all resources associated with the current skeleton
  83448. */
  83449. Skeleton.prototype.dispose = function () {
  83450. this._meshesWithPoseMatrix = [];
  83451. // Animations
  83452. this.getScene().stopAnimation(this);
  83453. // Remove from scene
  83454. this.getScene().removeSkeleton(this);
  83455. };
  83456. /**
  83457. * Serialize the skeleton in a JSON object
  83458. * @returns a JSON object
  83459. */
  83460. Skeleton.prototype.serialize = function () {
  83461. var serializationObject = {};
  83462. serializationObject.name = this.name;
  83463. serializationObject.id = this.id;
  83464. if (this.dimensionsAtRest) {
  83465. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  83466. }
  83467. serializationObject.bones = [];
  83468. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  83469. for (var index = 0; index < this.bones.length; index++) {
  83470. var bone = this.bones[index];
  83471. var parent_2 = bone.getParent();
  83472. var serializedBone = {
  83473. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  83474. name: bone.name,
  83475. matrix: bone.getBaseMatrix().toArray(),
  83476. rest: bone.getRestPose().toArray()
  83477. };
  83478. serializationObject.bones.push(serializedBone);
  83479. if (bone.length) {
  83480. serializedBone.length = bone.length;
  83481. }
  83482. if (bone.metadata) {
  83483. serializedBone.metadata = bone.metadata;
  83484. }
  83485. if (bone.animations && bone.animations.length > 0) {
  83486. serializedBone.animation = bone.animations[0].serialize();
  83487. }
  83488. serializationObject.ranges = [];
  83489. for (var name in this._ranges) {
  83490. var source = this._ranges[name];
  83491. if (!source) {
  83492. continue;
  83493. }
  83494. var range = {};
  83495. range.name = name;
  83496. range.from = source.from;
  83497. range.to = source.to;
  83498. serializationObject.ranges.push(range);
  83499. }
  83500. }
  83501. return serializationObject;
  83502. };
  83503. /**
  83504. * Creates a new skeleton from serialized data
  83505. * @param parsedSkeleton defines the serialized data
  83506. * @param scene defines the hosting scene
  83507. * @returns a new skeleton
  83508. */
  83509. Skeleton.Parse = function (parsedSkeleton, scene) {
  83510. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  83511. if (parsedSkeleton.dimensionsAtRest) {
  83512. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  83513. }
  83514. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  83515. var index;
  83516. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  83517. var parsedBone = parsedSkeleton.bones[index];
  83518. var parentBone = null;
  83519. if (parsedBone.parentBoneIndex > -1) {
  83520. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  83521. }
  83522. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  83523. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  83524. if (parsedBone.length) {
  83525. bone.length = parsedBone.length;
  83526. }
  83527. if (parsedBone.metadata) {
  83528. bone.metadata = parsedBone.metadata;
  83529. }
  83530. if (parsedBone.animation) {
  83531. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  83532. }
  83533. }
  83534. // placed after bones, so createAnimationRange can cascade down
  83535. if (parsedSkeleton.ranges) {
  83536. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  83537. var data = parsedSkeleton.ranges[index];
  83538. skeleton.createAnimationRange(data.name, data.from, data.to);
  83539. }
  83540. }
  83541. return skeleton;
  83542. };
  83543. /**
  83544. * Compute all node absolute transforms
  83545. * @param forceUpdate defines if computation must be done even if cache is up to date
  83546. */
  83547. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  83548. if (forceUpdate === void 0) { forceUpdate = false; }
  83549. var renderId = this._scene.getRenderId();
  83550. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  83551. this.bones[0].computeAbsoluteTransforms();
  83552. this._lastAbsoluteTransformsUpdateId = renderId;
  83553. }
  83554. };
  83555. /**
  83556. * Gets the root pose matrix
  83557. * @returns a matrix
  83558. */
  83559. Skeleton.prototype.getPoseMatrix = function () {
  83560. var poseMatrix = null;
  83561. if (this._meshesWithPoseMatrix.length > 0) {
  83562. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  83563. }
  83564. return poseMatrix;
  83565. };
  83566. /**
  83567. * Sorts bones per internal index
  83568. */
  83569. Skeleton.prototype.sortBones = function () {
  83570. var bones = new Array();
  83571. var visited = new Array(this.bones.length);
  83572. for (var index = 0; index < this.bones.length; index++) {
  83573. this._sortBones(index, bones, visited);
  83574. }
  83575. this.bones = bones;
  83576. };
  83577. Skeleton.prototype._sortBones = function (index, bones, visited) {
  83578. if (visited[index]) {
  83579. return;
  83580. }
  83581. visited[index] = true;
  83582. var bone = this.bones[index];
  83583. if (bone._index === undefined) {
  83584. bone._index = index;
  83585. }
  83586. var parentBone = bone.getParent();
  83587. if (parentBone) {
  83588. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  83589. }
  83590. bones.push(bone);
  83591. };
  83592. return Skeleton;
  83593. }());
  83594. BABYLON.Skeleton = Skeleton;
  83595. })(BABYLON || (BABYLON = {}));
  83596. //# sourceMappingURL=babylon.skeleton.js.map
  83597. var BABYLON;
  83598. (function (BABYLON) {
  83599. ;
  83600. /**
  83601. * This groups tools to convert HDR texture to native colors array.
  83602. */
  83603. var HDRTools = /** @class */ (function () {
  83604. function HDRTools() {
  83605. }
  83606. HDRTools.Ldexp = function (mantissa, exponent) {
  83607. if (exponent > 1023) {
  83608. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  83609. }
  83610. if (exponent < -1074) {
  83611. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  83612. }
  83613. return mantissa * Math.pow(2, exponent);
  83614. };
  83615. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  83616. if (exponent > 0) { /*nonzero pixel*/
  83617. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83618. float32array[index + 0] = red * exponent;
  83619. float32array[index + 1] = green * exponent;
  83620. float32array[index + 2] = blue * exponent;
  83621. }
  83622. else {
  83623. float32array[index + 0] = 0;
  83624. float32array[index + 1] = 0;
  83625. float32array[index + 2] = 0;
  83626. }
  83627. };
  83628. HDRTools.readStringLine = function (uint8array, startIndex) {
  83629. var line = "";
  83630. var character = "";
  83631. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83632. character = String.fromCharCode(uint8array[i]);
  83633. if (character == "\n") {
  83634. break;
  83635. }
  83636. line += character;
  83637. }
  83638. return line;
  83639. };
  83640. /**
  83641. * Reads header information from an RGBE texture stored in a native array.
  83642. * More information on this format are available here:
  83643. * https://en.wikipedia.org/wiki/RGBE_image_format
  83644. *
  83645. * @param uint8array The binary file stored in native array.
  83646. * @return The header information.
  83647. */
  83648. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83649. var height = 0;
  83650. var width = 0;
  83651. var line = this.readStringLine(uint8array, 0);
  83652. if (line[0] != '#' || line[1] != '?') {
  83653. throw "Bad HDR Format.";
  83654. }
  83655. var endOfHeader = false;
  83656. var findFormat = false;
  83657. var lineIndex = 0;
  83658. do {
  83659. lineIndex += (line.length + 1);
  83660. line = this.readStringLine(uint8array, lineIndex);
  83661. if (line == "FORMAT=32-bit_rle_rgbe") {
  83662. findFormat = true;
  83663. }
  83664. else if (line.length == 0) {
  83665. endOfHeader = true;
  83666. }
  83667. } while (!endOfHeader);
  83668. if (!findFormat) {
  83669. throw "HDR Bad header format, unsupported FORMAT";
  83670. }
  83671. lineIndex += (line.length + 1);
  83672. line = this.readStringLine(uint8array, lineIndex);
  83673. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83674. var match = sizeRegexp.exec(line);
  83675. // TODO. Support +Y and -X if needed.
  83676. if (!match || match.length < 3) {
  83677. throw "HDR Bad header format, no size";
  83678. }
  83679. width = parseInt(match[2]);
  83680. height = parseInt(match[1]);
  83681. if (width < 8 || width > 0x7fff) {
  83682. throw "HDR Bad header format, unsupported size";
  83683. }
  83684. lineIndex += (line.length + 1);
  83685. return {
  83686. height: height,
  83687. width: width,
  83688. dataPosition: lineIndex
  83689. };
  83690. };
  83691. /**
  83692. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83693. * This RGBE texture needs to store the information as a panorama.
  83694. *
  83695. * More information on this format are available here:
  83696. * https://en.wikipedia.org/wiki/RGBE_image_format
  83697. *
  83698. * @param buffer The binary file stored in an array buffer.
  83699. * @param size The expected size of the extracted cubemap.
  83700. * @return The Cube Map information.
  83701. */
  83702. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83703. var uint8array = new Uint8Array(buffer);
  83704. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83705. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83706. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83707. return cubeMapData;
  83708. };
  83709. /**
  83710. * Returns the pixels data extracted from an RGBE texture.
  83711. * This pixels will be stored left to right up to down in the R G B order in one array.
  83712. *
  83713. * More information on this format are available here:
  83714. * https://en.wikipedia.org/wiki/RGBE_image_format
  83715. *
  83716. * @param uint8array The binary file stored in an array buffer.
  83717. * @param hdrInfo The header information of the file.
  83718. * @return The pixels data in RGB right to left up to down order.
  83719. */
  83720. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83721. // Keep for multi format supports.
  83722. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83723. };
  83724. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83725. var num_scanlines = hdrInfo.height;
  83726. var scanline_width = hdrInfo.width;
  83727. var a, b, c, d, count;
  83728. var dataIndex = hdrInfo.dataPosition;
  83729. var index = 0, endIndex = 0, i = 0;
  83730. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83731. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83732. // 3 channels of 4 bytes per pixel in float.
  83733. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83734. var resultArray = new Float32Array(resultBuffer);
  83735. // read in each successive scanline
  83736. while (num_scanlines > 0) {
  83737. a = uint8array[dataIndex++];
  83738. b = uint8array[dataIndex++];
  83739. c = uint8array[dataIndex++];
  83740. d = uint8array[dataIndex++];
  83741. if (a != 2 || b != 2 || (c & 0x80)) {
  83742. // this file is not run length encoded
  83743. throw "HDR Bad header format, not RLE";
  83744. }
  83745. if (((c << 8) | d) != scanline_width) {
  83746. throw "HDR Bad header format, wrong scan line width";
  83747. }
  83748. index = 0;
  83749. // read each of the four channels for the scanline into the buffer
  83750. for (i = 0; i < 4; i++) {
  83751. endIndex = (i + 1) * scanline_width;
  83752. while (index < endIndex) {
  83753. a = uint8array[dataIndex++];
  83754. b = uint8array[dataIndex++];
  83755. if (a > 128) {
  83756. // a run of the same value
  83757. count = a - 128;
  83758. if ((count == 0) || (count > endIndex - index)) {
  83759. throw "HDR Bad Format, bad scanline data (run)";
  83760. }
  83761. while (count-- > 0) {
  83762. scanLineArray[index++] = b;
  83763. }
  83764. }
  83765. else {
  83766. // a non-run
  83767. count = a;
  83768. if ((count == 0) || (count > endIndex - index)) {
  83769. throw "HDR Bad Format, bad scanline data (non-run)";
  83770. }
  83771. scanLineArray[index++] = b;
  83772. if (--count > 0) {
  83773. for (var j = 0; j < count; j++) {
  83774. scanLineArray[index++] = uint8array[dataIndex++];
  83775. }
  83776. }
  83777. }
  83778. }
  83779. }
  83780. // now convert data from buffer into floats
  83781. for (i = 0; i < scanline_width; i++) {
  83782. a = scanLineArray[i];
  83783. b = scanLineArray[i + scanline_width];
  83784. c = scanLineArray[i + 2 * scanline_width];
  83785. d = scanLineArray[i + 3 * scanline_width];
  83786. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83787. }
  83788. num_scanlines--;
  83789. }
  83790. return resultArray;
  83791. };
  83792. return HDRTools;
  83793. }());
  83794. BABYLON.HDRTools = HDRTools;
  83795. })(BABYLON || (BABYLON = {}));
  83796. //# sourceMappingURL=babylon.hdr.js.map
  83797. var BABYLON;
  83798. (function (BABYLON) {
  83799. /**
  83800. * This represents a texture coming from an HDR input.
  83801. *
  83802. * The only supported format is currently panorama picture stored in RGBE format.
  83803. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83804. */
  83805. var HDRCubeTexture = /** @class */ (function (_super) {
  83806. __extends(HDRCubeTexture, _super);
  83807. /**
  83808. * Instantiates an HDRTexture from the following parameters.
  83809. *
  83810. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83811. * @param scene The scene the texture will be used in
  83812. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83813. * @param noMipmap Forces to not generate the mipmap if true
  83814. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83815. * @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)
  83816. * @param reserved Reserved flag for internal use.
  83817. */
  83818. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83819. if (noMipmap === void 0) { noMipmap = false; }
  83820. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83821. if (gammaSpace === void 0) { gammaSpace = false; }
  83822. if (reserved === void 0) { reserved = false; }
  83823. if (onLoad === void 0) { onLoad = null; }
  83824. if (onError === void 0) { onError = null; }
  83825. var _this = _super.call(this, scene) || this;
  83826. _this._generateHarmonics = true;
  83827. _this._onLoad = null;
  83828. _this._onError = null;
  83829. /**
  83830. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83831. */
  83832. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83833. _this._isBlocking = true;
  83834. _this._rotationY = 0;
  83835. /**
  83836. * Gets or sets the center of the bounding box associated with the cube texture
  83837. * It must define where the camera used to render the texture was set
  83838. */
  83839. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83840. if (!url) {
  83841. return _this;
  83842. }
  83843. _this.name = url;
  83844. _this.url = url;
  83845. _this.hasAlpha = false;
  83846. _this.isCube = true;
  83847. _this._textureMatrix = BABYLON.Matrix.Identity();
  83848. _this._onLoad = onLoad;
  83849. _this._onError = onError;
  83850. _this.gammaSpace = gammaSpace;
  83851. _this._noMipmap = noMipmap;
  83852. _this._size = size;
  83853. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83854. if (!_this._texture) {
  83855. if (!scene.useDelayedTextureLoading) {
  83856. _this.loadTexture();
  83857. }
  83858. else {
  83859. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83860. }
  83861. }
  83862. return _this;
  83863. }
  83864. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83865. /**
  83866. * Gets wether or not the texture is blocking during loading.
  83867. */
  83868. get: function () {
  83869. return this._isBlocking;
  83870. },
  83871. /**
  83872. * Sets wether or not the texture is blocking during loading.
  83873. */
  83874. set: function (value) {
  83875. this._isBlocking = value;
  83876. },
  83877. enumerable: true,
  83878. configurable: true
  83879. });
  83880. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83881. /**
  83882. * Gets texture matrix rotation angle around Y axis radians.
  83883. */
  83884. get: function () {
  83885. return this._rotationY;
  83886. },
  83887. /**
  83888. * Sets texture matrix rotation angle around Y axis in radians.
  83889. */
  83890. set: function (value) {
  83891. this._rotationY = value;
  83892. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83893. },
  83894. enumerable: true,
  83895. configurable: true
  83896. });
  83897. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83898. get: function () {
  83899. return this._boundingBoxSize;
  83900. },
  83901. /**
  83902. * Gets or sets the size of the bounding box associated with the cube texture
  83903. * When defined, the cubemap will switch to local mode
  83904. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83905. * @example https://www.babylonjs-playground.com/#RNASML
  83906. */
  83907. set: function (value) {
  83908. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83909. return;
  83910. }
  83911. this._boundingBoxSize = value;
  83912. var scene = this.getScene();
  83913. if (scene) {
  83914. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83915. }
  83916. },
  83917. enumerable: true,
  83918. configurable: true
  83919. });
  83920. /**
  83921. * Occurs when the file is raw .hdr file.
  83922. */
  83923. HDRCubeTexture.prototype.loadTexture = function () {
  83924. var _this = this;
  83925. var callback = function (buffer) {
  83926. _this.lodGenerationOffset = 0.0;
  83927. _this.lodGenerationScale = 0.8;
  83928. var scene = _this.getScene();
  83929. if (!scene) {
  83930. return null;
  83931. }
  83932. // Extract the raw linear data.
  83933. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83934. // Generate harmonics if needed.
  83935. if (_this._generateHarmonics) {
  83936. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83937. _this.sphericalPolynomial = sphericalPolynomial;
  83938. }
  83939. var results = [];
  83940. var byteArray = null;
  83941. // Push each faces.
  83942. for (var j = 0; j < 6; j++) {
  83943. // Create uintarray fallback.
  83944. if (!scene.getEngine().getCaps().textureFloat) {
  83945. // 3 channels of 1 bytes per pixel in bytes.
  83946. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83947. byteArray = new Uint8Array(byteBuffer);
  83948. }
  83949. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83950. // If special cases.
  83951. if (_this.gammaSpace || byteArray) {
  83952. for (var i = 0; i < _this._size * _this._size; i++) {
  83953. // Put in gamma space if requested.
  83954. if (_this.gammaSpace) {
  83955. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83956. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83957. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83958. }
  83959. // Convert to int texture for fallback.
  83960. if (byteArray) {
  83961. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83962. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83963. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83964. // May use luminance instead if the result is not accurate.
  83965. var max = Math.max(Math.max(r, g), b);
  83966. if (max > 255) {
  83967. var scale = 255 / max;
  83968. r *= scale;
  83969. g *= scale;
  83970. b *= scale;
  83971. }
  83972. byteArray[(i * 3) + 0] = r;
  83973. byteArray[(i * 3) + 1] = g;
  83974. byteArray[(i * 3) + 2] = b;
  83975. }
  83976. }
  83977. }
  83978. if (byteArray) {
  83979. results.push(byteArray);
  83980. }
  83981. else {
  83982. results.push(dataFace);
  83983. }
  83984. }
  83985. return results;
  83986. };
  83987. var scene = this.getScene();
  83988. if (scene) {
  83989. 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);
  83990. }
  83991. };
  83992. HDRCubeTexture.prototype.clone = function () {
  83993. var scene = this.getScene();
  83994. if (!scene) {
  83995. return this;
  83996. }
  83997. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83998. // Base texture
  83999. newTexture.level = this.level;
  84000. newTexture.wrapU = this.wrapU;
  84001. newTexture.wrapV = this.wrapV;
  84002. newTexture.coordinatesIndex = this.coordinatesIndex;
  84003. newTexture.coordinatesMode = this.coordinatesMode;
  84004. return newTexture;
  84005. };
  84006. // Methods
  84007. HDRCubeTexture.prototype.delayLoad = function () {
  84008. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84009. return;
  84010. }
  84011. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84012. this._texture = this._getFromCache(this.url, this._noMipmap);
  84013. if (!this._texture) {
  84014. this.loadTexture();
  84015. }
  84016. };
  84017. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  84018. return this._textureMatrix;
  84019. };
  84020. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  84021. this._textureMatrix = value;
  84022. };
  84023. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84024. var texture = null;
  84025. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84026. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  84027. texture.name = parsedTexture.name;
  84028. texture.hasAlpha = parsedTexture.hasAlpha;
  84029. texture.level = parsedTexture.level;
  84030. texture.coordinatesMode = parsedTexture.coordinatesMode;
  84031. texture.isBlocking = parsedTexture.isBlocking;
  84032. }
  84033. if (texture) {
  84034. if (parsedTexture.boundingBoxPosition) {
  84035. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  84036. }
  84037. if (parsedTexture.boundingBoxSize) {
  84038. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  84039. }
  84040. if (parsedTexture.rotationY) {
  84041. texture.rotationY = parsedTexture.rotationY;
  84042. }
  84043. }
  84044. return texture;
  84045. };
  84046. HDRCubeTexture.prototype.serialize = function () {
  84047. if (!this.name) {
  84048. return null;
  84049. }
  84050. var serializationObject = {};
  84051. serializationObject.name = this.name;
  84052. serializationObject.hasAlpha = this.hasAlpha;
  84053. serializationObject.isCube = true;
  84054. serializationObject.level = this.level;
  84055. serializationObject.size = this._size;
  84056. serializationObject.coordinatesMode = this.coordinatesMode;
  84057. serializationObject.useInGammaSpace = this.gammaSpace;
  84058. serializationObject.generateHarmonics = this._generateHarmonics;
  84059. serializationObject.customType = "BABYLON.HDRCubeTexture";
  84060. serializationObject.noMipmap = this._noMipmap;
  84061. serializationObject.isBlocking = this._isBlocking;
  84062. serializationObject.rotationY = this._rotationY;
  84063. return serializationObject;
  84064. };
  84065. HDRCubeTexture._facesMapping = [
  84066. "right",
  84067. "left",
  84068. "up",
  84069. "down",
  84070. "front",
  84071. "back"
  84072. ];
  84073. return HDRCubeTexture;
  84074. }(BABYLON.BaseTexture));
  84075. BABYLON.HDRCubeTexture = HDRCubeTexture;
  84076. })(BABYLON || (BABYLON = {}));
  84077. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  84078. var BABYLON;
  84079. (function (BABYLON) {
  84080. /**
  84081. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  84082. */
  84083. var PanoramaToCubeMapTools = /** @class */ (function () {
  84084. function PanoramaToCubeMapTools() {
  84085. }
  84086. /**
  84087. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  84088. *
  84089. * @param float32Array The source data.
  84090. * @param inputWidth The width of the input panorama.
  84091. * @param inputhHeight The height of the input panorama.
  84092. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  84093. * @return The cubemap data
  84094. */
  84095. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  84096. if (!float32Array) {
  84097. throw "ConvertPanoramaToCubemap: input cannot be null";
  84098. }
  84099. if (float32Array.length != inputWidth * inputHeight * 3) {
  84100. throw "ConvertPanoramaToCubemap: input size is wrong";
  84101. }
  84102. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  84103. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  84104. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  84105. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  84106. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  84107. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  84108. return {
  84109. front: textureFront,
  84110. back: textureBack,
  84111. left: textureLeft,
  84112. right: textureRight,
  84113. up: textureUp,
  84114. down: textureDown,
  84115. size: size,
  84116. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84117. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  84118. gammaSpace: false,
  84119. };
  84120. };
  84121. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  84122. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  84123. var textureArray = new Float32Array(buffer);
  84124. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  84125. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  84126. var dy = 1 / texSize;
  84127. var fy = 0;
  84128. for (var y = 0; y < texSize; y++) {
  84129. var xv1 = faceData[0];
  84130. var xv2 = faceData[2];
  84131. for (var x = 0; x < texSize; x++) {
  84132. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  84133. v.normalize();
  84134. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  84135. // 3 channels per pixels
  84136. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  84137. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  84138. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  84139. xv1 = xv1.add(rotDX1);
  84140. xv2 = xv2.add(rotDX2);
  84141. }
  84142. fy += dy;
  84143. }
  84144. return textureArray;
  84145. };
  84146. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  84147. var theta = Math.atan2(vDir.z, vDir.x);
  84148. var phi = Math.acos(vDir.y);
  84149. while (theta < -Math.PI)
  84150. theta += 2 * Math.PI;
  84151. while (theta > Math.PI)
  84152. theta -= 2 * Math.PI;
  84153. var dx = theta / Math.PI;
  84154. var dy = phi / Math.PI;
  84155. // recenter.
  84156. dx = dx * 0.5 + 0.5;
  84157. var px = Math.round(dx * inputWidth);
  84158. if (px < 0)
  84159. px = 0;
  84160. else if (px >= inputWidth)
  84161. px = inputWidth - 1;
  84162. var py = Math.round(dy * inputHeight);
  84163. if (py < 0)
  84164. py = 0;
  84165. else if (py >= inputHeight)
  84166. py = inputHeight - 1;
  84167. var inputY = (inputHeight - py - 1);
  84168. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  84169. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  84170. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  84171. return {
  84172. r: r,
  84173. g: g,
  84174. b: b
  84175. };
  84176. };
  84177. PanoramaToCubeMapTools.FACE_FRONT = [
  84178. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84179. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84180. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84181. new BABYLON.Vector3(1.0, 1.0, -1.0)
  84182. ];
  84183. PanoramaToCubeMapTools.FACE_BACK = [
  84184. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84185. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84186. new BABYLON.Vector3(1.0, 1.0, 1.0),
  84187. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  84188. ];
  84189. PanoramaToCubeMapTools.FACE_RIGHT = [
  84190. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84191. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84192. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84193. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84194. ];
  84195. PanoramaToCubeMapTools.FACE_LEFT = [
  84196. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84197. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84198. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84199. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  84200. ];
  84201. PanoramaToCubeMapTools.FACE_DOWN = [
  84202. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84203. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84204. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84205. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84206. ];
  84207. PanoramaToCubeMapTools.FACE_UP = [
  84208. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84209. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84210. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84211. new BABYLON.Vector3(1.0, -1.0, -1.0)
  84212. ];
  84213. return PanoramaToCubeMapTools;
  84214. }());
  84215. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  84216. })(BABYLON || (BABYLON = {}));
  84217. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  84218. var BABYLON;
  84219. (function (BABYLON) {
  84220. var IndexedVector2 = /** @class */ (function (_super) {
  84221. __extends(IndexedVector2, _super);
  84222. function IndexedVector2(original, index) {
  84223. var _this = _super.call(this, original.x, original.y) || this;
  84224. _this.index = index;
  84225. return _this;
  84226. }
  84227. return IndexedVector2;
  84228. }(BABYLON.Vector2));
  84229. var PolygonPoints = /** @class */ (function () {
  84230. function PolygonPoints() {
  84231. this.elements = new Array();
  84232. }
  84233. PolygonPoints.prototype.add = function (originalPoints) {
  84234. var _this = this;
  84235. var result = new Array();
  84236. originalPoints.forEach(function (point) {
  84237. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  84238. var newPoint = new IndexedVector2(point, _this.elements.length);
  84239. result.push(newPoint);
  84240. _this.elements.push(newPoint);
  84241. }
  84242. });
  84243. return result;
  84244. };
  84245. PolygonPoints.prototype.computeBounds = function () {
  84246. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84247. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84248. this.elements.forEach(function (point) {
  84249. // x
  84250. if (point.x < lmin.x) {
  84251. lmin.x = point.x;
  84252. }
  84253. else if (point.x > lmax.x) {
  84254. lmax.x = point.x;
  84255. }
  84256. // y
  84257. if (point.y < lmin.y) {
  84258. lmin.y = point.y;
  84259. }
  84260. else if (point.y > lmax.y) {
  84261. lmax.y = point.y;
  84262. }
  84263. });
  84264. return {
  84265. min: lmin,
  84266. max: lmax,
  84267. width: lmax.x - lmin.x,
  84268. height: lmax.y - lmin.y
  84269. };
  84270. };
  84271. return PolygonPoints;
  84272. }());
  84273. var Polygon = /** @class */ (function () {
  84274. function Polygon() {
  84275. }
  84276. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  84277. return [
  84278. new BABYLON.Vector2(xmin, ymin),
  84279. new BABYLON.Vector2(xmax, ymin),
  84280. new BABYLON.Vector2(xmax, ymax),
  84281. new BABYLON.Vector2(xmin, ymax)
  84282. ];
  84283. };
  84284. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  84285. if (cx === void 0) { cx = 0; }
  84286. if (cy === void 0) { cy = 0; }
  84287. if (numberOfSides === void 0) { numberOfSides = 32; }
  84288. var result = new Array();
  84289. var angle = 0;
  84290. var increment = (Math.PI * 2) / numberOfSides;
  84291. for (var i = 0; i < numberOfSides; i++) {
  84292. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  84293. angle -= increment;
  84294. }
  84295. return result;
  84296. };
  84297. Polygon.Parse = function (input) {
  84298. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  84299. var i, result = [];
  84300. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  84301. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  84302. }
  84303. return result;
  84304. };
  84305. Polygon.StartingAt = function (x, y) {
  84306. return BABYLON.Path2.StartingAt(x, y);
  84307. };
  84308. return Polygon;
  84309. }());
  84310. BABYLON.Polygon = Polygon;
  84311. var PolygonMeshBuilder = /** @class */ (function () {
  84312. function PolygonMeshBuilder(name, contours, scene) {
  84313. this._points = new PolygonPoints();
  84314. this._outlinepoints = new PolygonPoints();
  84315. this._holes = new Array();
  84316. this._epoints = new Array();
  84317. this._eholes = new Array();
  84318. this._name = name;
  84319. this._scene = scene;
  84320. var points;
  84321. if (contours instanceof BABYLON.Path2) {
  84322. points = contours.getPoints();
  84323. }
  84324. else {
  84325. points = contours;
  84326. }
  84327. this._addToepoint(points);
  84328. this._points.add(points);
  84329. this._outlinepoints.add(points);
  84330. if (typeof earcut === 'undefined') {
  84331. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  84332. }
  84333. }
  84334. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  84335. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  84336. var p = points_1[_i];
  84337. this._epoints.push(p.x, p.y);
  84338. }
  84339. };
  84340. PolygonMeshBuilder.prototype.addHole = function (hole) {
  84341. this._points.add(hole);
  84342. var holepoints = new PolygonPoints();
  84343. holepoints.add(hole);
  84344. this._holes.push(holepoints);
  84345. this._eholes.push(this._epoints.length / 2);
  84346. this._addToepoint(hole);
  84347. return this;
  84348. };
  84349. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  84350. var _this = this;
  84351. if (updatable === void 0) { updatable = false; }
  84352. if (depth === void 0) { depth = 0; }
  84353. var result = new BABYLON.Mesh(this._name, this._scene);
  84354. var normals = new Array();
  84355. var positions = new Array();
  84356. var uvs = new Array();
  84357. var bounds = this._points.computeBounds();
  84358. this._points.elements.forEach(function (p) {
  84359. normals.push(0, 1.0, 0);
  84360. positions.push(p.x, 0, p.y);
  84361. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  84362. });
  84363. var indices = new Array();
  84364. var res = earcut(this._epoints, this._eholes, 2);
  84365. for (var i = 0; i < res.length; i++) {
  84366. indices.push(res[i]);
  84367. }
  84368. if (depth > 0) {
  84369. var positionscount = (positions.length / 3); //get the current pointcount
  84370. this._points.elements.forEach(function (p) {
  84371. normals.push(0, -1.0, 0);
  84372. positions.push(p.x, -depth, p.y);
  84373. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  84374. });
  84375. var totalCount = indices.length;
  84376. for (var i = 0; i < totalCount; i += 3) {
  84377. var i0 = indices[i + 0];
  84378. var i1 = indices[i + 1];
  84379. var i2 = indices[i + 2];
  84380. indices.push(i2 + positionscount);
  84381. indices.push(i1 + positionscount);
  84382. indices.push(i0 + positionscount);
  84383. }
  84384. //Add the sides
  84385. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  84386. this._holes.forEach(function (hole) {
  84387. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  84388. });
  84389. }
  84390. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  84391. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  84392. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  84393. result.setIndices(indices);
  84394. return result;
  84395. };
  84396. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  84397. var StartIndex = positions.length / 3;
  84398. var ulength = 0;
  84399. for (var i = 0; i < points.elements.length; i++) {
  84400. var p = points.elements[i];
  84401. var p1;
  84402. if ((i + 1) > points.elements.length - 1) {
  84403. p1 = points.elements[0];
  84404. }
  84405. else {
  84406. p1 = points.elements[i + 1];
  84407. }
  84408. positions.push(p.x, 0, p.y);
  84409. positions.push(p.x, -depth, p.y);
  84410. positions.push(p1.x, 0, p1.y);
  84411. positions.push(p1.x, -depth, p1.y);
  84412. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  84413. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  84414. var v3 = v2.subtract(v1);
  84415. var v4 = new BABYLON.Vector3(0, 1, 0);
  84416. var vn = BABYLON.Vector3.Cross(v3, v4);
  84417. vn = vn.normalize();
  84418. uvs.push(ulength / bounds.width, 0);
  84419. uvs.push(ulength / bounds.width, 1);
  84420. ulength += v3.length();
  84421. uvs.push((ulength / bounds.width), 0);
  84422. uvs.push((ulength / bounds.width), 1);
  84423. if (!flip) {
  84424. normals.push(-vn.x, -vn.y, -vn.z);
  84425. normals.push(-vn.x, -vn.y, -vn.z);
  84426. normals.push(-vn.x, -vn.y, -vn.z);
  84427. normals.push(-vn.x, -vn.y, -vn.z);
  84428. indices.push(StartIndex);
  84429. indices.push(StartIndex + 1);
  84430. indices.push(StartIndex + 2);
  84431. indices.push(StartIndex + 1);
  84432. indices.push(StartIndex + 3);
  84433. indices.push(StartIndex + 2);
  84434. }
  84435. else {
  84436. normals.push(vn.x, vn.y, vn.z);
  84437. normals.push(vn.x, vn.y, vn.z);
  84438. normals.push(vn.x, vn.y, vn.z);
  84439. normals.push(vn.x, vn.y, vn.z);
  84440. indices.push(StartIndex);
  84441. indices.push(StartIndex + 2);
  84442. indices.push(StartIndex + 1);
  84443. indices.push(StartIndex + 1);
  84444. indices.push(StartIndex + 2);
  84445. indices.push(StartIndex + 3);
  84446. }
  84447. StartIndex += 4;
  84448. }
  84449. ;
  84450. };
  84451. return PolygonMeshBuilder;
  84452. }());
  84453. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  84454. })(BABYLON || (BABYLON = {}));
  84455. //# sourceMappingURL=babylon.polygonMesh.js.map
  84456. var BABYLON;
  84457. (function (BABYLON) {
  84458. // Unique ID when we import meshes from Babylon to CSG
  84459. var currentCSGMeshId = 0;
  84460. // # class Vertex
  84461. // Represents a vertex of a polygon. Use your own vertex class instead of this
  84462. // one to provide additional features like texture coordinates and vertex
  84463. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  84464. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  84465. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  84466. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  84467. // is not used anywhere else.
  84468. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  84469. var Vertex = /** @class */ (function () {
  84470. function Vertex(pos, normal, uv) {
  84471. this.pos = pos;
  84472. this.normal = normal;
  84473. this.uv = uv;
  84474. }
  84475. Vertex.prototype.clone = function () {
  84476. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  84477. };
  84478. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  84479. // orientation of a polygon is flipped.
  84480. Vertex.prototype.flip = function () {
  84481. this.normal = this.normal.scale(-1);
  84482. };
  84483. // Create a new vertex between this vertex and `other` by linearly
  84484. // interpolating all properties using a parameter of `t`. Subclasses should
  84485. // override this to interpolate additional properties.
  84486. Vertex.prototype.interpolate = function (other, t) {
  84487. 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));
  84488. };
  84489. return Vertex;
  84490. }());
  84491. // # class Plane
  84492. // Represents a plane in 3D space.
  84493. var Plane = /** @class */ (function () {
  84494. function Plane(normal, w) {
  84495. this.normal = normal;
  84496. this.w = w;
  84497. }
  84498. Plane.FromPoints = function (a, b, c) {
  84499. var v0 = c.subtract(a);
  84500. var v1 = b.subtract(a);
  84501. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  84502. return null;
  84503. }
  84504. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  84505. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  84506. };
  84507. Plane.prototype.clone = function () {
  84508. return new Plane(this.normal.clone(), this.w);
  84509. };
  84510. Plane.prototype.flip = function () {
  84511. this.normal.scaleInPlace(-1);
  84512. this.w = -this.w;
  84513. };
  84514. // Split `polygon` by this plane if needed, then put the polygon or polygon
  84515. // fragments in the appropriate lists. Coplanar polygons go into either
  84516. // `coplanarFront` or `coplanarBack` depending on their orientation with
  84517. // respect to this plane. Polygons in front or in back of this plane go into
  84518. // either `front` or `back`.
  84519. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  84520. var COPLANAR = 0;
  84521. var FRONT = 1;
  84522. var BACK = 2;
  84523. var SPANNING = 3;
  84524. // Classify each point as well as the entire polygon into one of the above
  84525. // four classes.
  84526. var polygonType = 0;
  84527. var types = [];
  84528. var i;
  84529. var t;
  84530. for (i = 0; i < polygon.vertices.length; i++) {
  84531. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  84532. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  84533. polygonType |= type;
  84534. types.push(type);
  84535. }
  84536. // Put the polygon in the correct list, splitting it when necessary.
  84537. switch (polygonType) {
  84538. case COPLANAR:
  84539. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  84540. break;
  84541. case FRONT:
  84542. front.push(polygon);
  84543. break;
  84544. case BACK:
  84545. back.push(polygon);
  84546. break;
  84547. case SPANNING:
  84548. var f = [], b = [];
  84549. for (i = 0; i < polygon.vertices.length; i++) {
  84550. var j = (i + 1) % polygon.vertices.length;
  84551. var ti = types[i], tj = types[j];
  84552. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  84553. if (ti !== BACK)
  84554. f.push(vi);
  84555. if (ti !== FRONT)
  84556. b.push(ti !== BACK ? vi.clone() : vi);
  84557. if ((ti | tj) === SPANNING) {
  84558. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  84559. var v = vi.interpolate(vj, t);
  84560. f.push(v);
  84561. b.push(v.clone());
  84562. }
  84563. }
  84564. var poly;
  84565. if (f.length >= 3) {
  84566. poly = new Polygon(f, polygon.shared);
  84567. if (poly.plane)
  84568. front.push(poly);
  84569. }
  84570. if (b.length >= 3) {
  84571. poly = new Polygon(b, polygon.shared);
  84572. if (poly.plane)
  84573. back.push(poly);
  84574. }
  84575. break;
  84576. }
  84577. };
  84578. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  84579. // point is on the plane.
  84580. Plane.EPSILON = 1e-5;
  84581. return Plane;
  84582. }());
  84583. // # class Polygon
  84584. // Represents a convex polygon. The vertices used to initialize a polygon must
  84585. // be coplanar and form a convex loop.
  84586. //
  84587. // Each convex polygon has a `shared` property, which is shared between all
  84588. // polygons that are clones of each other or were split from the same polygon.
  84589. // This can be used to define per-polygon properties (such as surface color).
  84590. var Polygon = /** @class */ (function () {
  84591. function Polygon(vertices, shared) {
  84592. this.vertices = vertices;
  84593. this.shared = shared;
  84594. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  84595. }
  84596. Polygon.prototype.clone = function () {
  84597. var vertices = this.vertices.map(function (v) { return v.clone(); });
  84598. return new Polygon(vertices, this.shared);
  84599. };
  84600. Polygon.prototype.flip = function () {
  84601. this.vertices.reverse().map(function (v) { v.flip(); });
  84602. this.plane.flip();
  84603. };
  84604. return Polygon;
  84605. }());
  84606. // # class Node
  84607. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  84608. // by picking a polygon to split along. That polygon (and all other coplanar
  84609. // polygons) are added directly to that node and the other polygons are added to
  84610. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  84611. // no distinction between internal and leaf nodes.
  84612. var Node = /** @class */ (function () {
  84613. function Node(polygons) {
  84614. this.plane = null;
  84615. this.front = null;
  84616. this.back = null;
  84617. this.polygons = new Array();
  84618. if (polygons) {
  84619. this.build(polygons);
  84620. }
  84621. }
  84622. Node.prototype.clone = function () {
  84623. var node = new Node();
  84624. node.plane = this.plane && this.plane.clone();
  84625. node.front = this.front && this.front.clone();
  84626. node.back = this.back && this.back.clone();
  84627. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84628. return node;
  84629. };
  84630. // Convert solid space to empty space and empty space to solid space.
  84631. Node.prototype.invert = function () {
  84632. for (var i = 0; i < this.polygons.length; i++) {
  84633. this.polygons[i].flip();
  84634. }
  84635. if (this.plane) {
  84636. this.plane.flip();
  84637. }
  84638. if (this.front) {
  84639. this.front.invert();
  84640. }
  84641. if (this.back) {
  84642. this.back.invert();
  84643. }
  84644. var temp = this.front;
  84645. this.front = this.back;
  84646. this.back = temp;
  84647. };
  84648. // Recursively remove all polygons in `polygons` that are inside this BSP
  84649. // tree.
  84650. Node.prototype.clipPolygons = function (polygons) {
  84651. if (!this.plane)
  84652. return polygons.slice();
  84653. var front = new Array(), back = new Array();
  84654. for (var i = 0; i < polygons.length; i++) {
  84655. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84656. }
  84657. if (this.front) {
  84658. front = this.front.clipPolygons(front);
  84659. }
  84660. if (this.back) {
  84661. back = this.back.clipPolygons(back);
  84662. }
  84663. else {
  84664. back = [];
  84665. }
  84666. return front.concat(back);
  84667. };
  84668. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84669. // `bsp`.
  84670. Node.prototype.clipTo = function (bsp) {
  84671. this.polygons = bsp.clipPolygons(this.polygons);
  84672. if (this.front)
  84673. this.front.clipTo(bsp);
  84674. if (this.back)
  84675. this.back.clipTo(bsp);
  84676. };
  84677. // Return a list of all polygons in this BSP tree.
  84678. Node.prototype.allPolygons = function () {
  84679. var polygons = this.polygons.slice();
  84680. if (this.front)
  84681. polygons = polygons.concat(this.front.allPolygons());
  84682. if (this.back)
  84683. polygons = polygons.concat(this.back.allPolygons());
  84684. return polygons;
  84685. };
  84686. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84687. // new polygons are filtered down to the bottom of the tree and become new
  84688. // nodes there. Each set of polygons is partitioned using the first polygon
  84689. // (no heuristic is used to pick a good split).
  84690. Node.prototype.build = function (polygons) {
  84691. if (!polygons.length)
  84692. return;
  84693. if (!this.plane)
  84694. this.plane = polygons[0].plane.clone();
  84695. var front = new Array(), back = new Array();
  84696. for (var i = 0; i < polygons.length; i++) {
  84697. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84698. }
  84699. if (front.length) {
  84700. if (!this.front)
  84701. this.front = new Node();
  84702. this.front.build(front);
  84703. }
  84704. if (back.length) {
  84705. if (!this.back)
  84706. this.back = new Node();
  84707. this.back.build(back);
  84708. }
  84709. };
  84710. return Node;
  84711. }());
  84712. var CSG = /** @class */ (function () {
  84713. function CSG() {
  84714. this.polygons = new Array();
  84715. }
  84716. // Convert BABYLON.Mesh to BABYLON.CSG
  84717. CSG.FromMesh = function (mesh) {
  84718. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84719. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84720. if (mesh instanceof BABYLON.Mesh) {
  84721. mesh.computeWorldMatrix(true);
  84722. matrix = mesh.getWorldMatrix();
  84723. meshPosition = mesh.position.clone();
  84724. meshRotation = mesh.rotation.clone();
  84725. if (mesh.rotationQuaternion) {
  84726. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84727. }
  84728. meshScaling = mesh.scaling.clone();
  84729. }
  84730. else {
  84731. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84732. }
  84733. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84734. var subMeshes = mesh.subMeshes;
  84735. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84736. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84737. vertices = [];
  84738. for (var j = 0; j < 3; j++) {
  84739. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84740. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84741. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84742. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84743. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84744. vertex = new Vertex(position, normal, uv);
  84745. vertices.push(vertex);
  84746. }
  84747. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84748. // To handle the case of degenerated triangle
  84749. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84750. if (polygon.plane)
  84751. polygons.push(polygon);
  84752. }
  84753. }
  84754. var csg = CSG.FromPolygons(polygons);
  84755. csg.matrix = matrix;
  84756. csg.position = meshPosition;
  84757. csg.rotation = meshRotation;
  84758. csg.scaling = meshScaling;
  84759. csg.rotationQuaternion = meshRotationQuaternion;
  84760. currentCSGMeshId++;
  84761. return csg;
  84762. };
  84763. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84764. CSG.FromPolygons = function (polygons) {
  84765. var csg = new CSG();
  84766. csg.polygons = polygons;
  84767. return csg;
  84768. };
  84769. CSG.prototype.clone = function () {
  84770. var csg = new CSG();
  84771. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84772. csg.copyTransformAttributes(this);
  84773. return csg;
  84774. };
  84775. CSG.prototype.union = function (csg) {
  84776. var a = new Node(this.clone().polygons);
  84777. var b = new Node(csg.clone().polygons);
  84778. a.clipTo(b);
  84779. b.clipTo(a);
  84780. b.invert();
  84781. b.clipTo(a);
  84782. b.invert();
  84783. a.build(b.allPolygons());
  84784. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84785. };
  84786. CSG.prototype.unionInPlace = function (csg) {
  84787. var a = new Node(this.polygons);
  84788. var b = new Node(csg.polygons);
  84789. a.clipTo(b);
  84790. b.clipTo(a);
  84791. b.invert();
  84792. b.clipTo(a);
  84793. b.invert();
  84794. a.build(b.allPolygons());
  84795. this.polygons = a.allPolygons();
  84796. };
  84797. CSG.prototype.subtract = function (csg) {
  84798. var a = new Node(this.clone().polygons);
  84799. var b = new Node(csg.clone().polygons);
  84800. a.invert();
  84801. a.clipTo(b);
  84802. b.clipTo(a);
  84803. b.invert();
  84804. b.clipTo(a);
  84805. b.invert();
  84806. a.build(b.allPolygons());
  84807. a.invert();
  84808. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84809. };
  84810. CSG.prototype.subtractInPlace = function (csg) {
  84811. var a = new Node(this.polygons);
  84812. var b = new Node(csg.polygons);
  84813. a.invert();
  84814. a.clipTo(b);
  84815. b.clipTo(a);
  84816. b.invert();
  84817. b.clipTo(a);
  84818. b.invert();
  84819. a.build(b.allPolygons());
  84820. a.invert();
  84821. this.polygons = a.allPolygons();
  84822. };
  84823. CSG.prototype.intersect = function (csg) {
  84824. var a = new Node(this.clone().polygons);
  84825. var b = new Node(csg.clone().polygons);
  84826. a.invert();
  84827. b.clipTo(a);
  84828. b.invert();
  84829. a.clipTo(b);
  84830. b.clipTo(a);
  84831. a.build(b.allPolygons());
  84832. a.invert();
  84833. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84834. };
  84835. CSG.prototype.intersectInPlace = function (csg) {
  84836. var a = new Node(this.polygons);
  84837. var b = new Node(csg.polygons);
  84838. a.invert();
  84839. b.clipTo(a);
  84840. b.invert();
  84841. a.clipTo(b);
  84842. b.clipTo(a);
  84843. a.build(b.allPolygons());
  84844. a.invert();
  84845. this.polygons = a.allPolygons();
  84846. };
  84847. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84848. // not modified.
  84849. CSG.prototype.inverse = function () {
  84850. var csg = this.clone();
  84851. csg.inverseInPlace();
  84852. return csg;
  84853. };
  84854. CSG.prototype.inverseInPlace = function () {
  84855. this.polygons.map(function (p) { p.flip(); });
  84856. };
  84857. // This is used to keep meshes transformations so they can be restored
  84858. // when we build back a Babylon Mesh
  84859. // NB : All CSG operations are performed in world coordinates
  84860. CSG.prototype.copyTransformAttributes = function (csg) {
  84861. this.matrix = csg.matrix;
  84862. this.position = csg.position;
  84863. this.rotation = csg.rotation;
  84864. this.scaling = csg.scaling;
  84865. this.rotationQuaternion = csg.rotationQuaternion;
  84866. return this;
  84867. };
  84868. // Build Raw mesh from CSG
  84869. // Coordinates here are in world space
  84870. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84871. var matrix = this.matrix.clone();
  84872. matrix.invert();
  84873. 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;
  84874. if (keepSubMeshes) {
  84875. // Sort Polygons, since subMeshes are indices range
  84876. polygons.sort(function (a, b) {
  84877. if (a.shared.meshId === b.shared.meshId) {
  84878. return a.shared.subMeshId - b.shared.subMeshId;
  84879. }
  84880. else {
  84881. return a.shared.meshId - b.shared.meshId;
  84882. }
  84883. });
  84884. }
  84885. for (var i = 0, il = polygons.length; i < il; i++) {
  84886. polygon = polygons[i];
  84887. // Building SubMeshes
  84888. if (!subMesh_dict[polygon.shared.meshId]) {
  84889. subMesh_dict[polygon.shared.meshId] = {};
  84890. }
  84891. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84892. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84893. indexStart: +Infinity,
  84894. indexEnd: -Infinity,
  84895. materialIndex: polygon.shared.materialIndex
  84896. };
  84897. }
  84898. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84899. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84900. polygonIndices[0] = 0;
  84901. polygonIndices[1] = j - 1;
  84902. polygonIndices[2] = j;
  84903. for (var k = 0; k < 3; k++) {
  84904. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84905. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84906. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84907. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84908. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84909. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84910. // Check if 2 points can be merged
  84911. if (!(typeof vertex_idx !== 'undefined' &&
  84912. normals[vertex_idx * 3] === localNormal.x &&
  84913. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84914. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84915. uvs[vertex_idx * 2] === uv.x &&
  84916. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84917. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84918. uvs.push(uv.x, uv.y);
  84919. normals.push(normal.x, normal.y, normal.z);
  84920. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84921. }
  84922. indices.push(vertex_idx);
  84923. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84924. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84925. currentIndex++;
  84926. }
  84927. }
  84928. }
  84929. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84930. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84931. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84932. mesh.setIndices(indices, null);
  84933. if (keepSubMeshes) {
  84934. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84935. var materialIndexOffset = 0, materialMaxIndex;
  84936. mesh.subMeshes = new Array();
  84937. for (var m in subMesh_dict) {
  84938. materialMaxIndex = -1;
  84939. for (var sm in subMesh_dict[m]) {
  84940. subMesh_obj = subMesh_dict[m][sm];
  84941. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84942. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84943. }
  84944. materialIndexOffset += ++materialMaxIndex;
  84945. }
  84946. }
  84947. return mesh;
  84948. };
  84949. // Build Mesh from CSG taking material and transforms into account
  84950. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84951. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84952. mesh.material = material;
  84953. mesh.position.copyFrom(this.position);
  84954. mesh.rotation.copyFrom(this.rotation);
  84955. if (this.rotationQuaternion) {
  84956. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84957. }
  84958. mesh.scaling.copyFrom(this.scaling);
  84959. mesh.computeWorldMatrix(true);
  84960. return mesh;
  84961. };
  84962. return CSG;
  84963. }());
  84964. BABYLON.CSG = CSG;
  84965. })(BABYLON || (BABYLON = {}));
  84966. //# sourceMappingURL=babylon.csg.js.map
  84967. var BABYLON;
  84968. (function (BABYLON) {
  84969. var LensFlare = /** @class */ (function () {
  84970. function LensFlare(size, position, color, imgUrl, system) {
  84971. this.size = size;
  84972. this.position = position;
  84973. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84974. this.color = color || new BABYLON.Color3(1, 1, 1);
  84975. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84976. this._system = system;
  84977. system.lensFlares.push(this);
  84978. }
  84979. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84980. return new LensFlare(size, position, color, imgUrl, system);
  84981. };
  84982. LensFlare.prototype.dispose = function () {
  84983. if (this.texture) {
  84984. this.texture.dispose();
  84985. }
  84986. // Remove from scene
  84987. var index = this._system.lensFlares.indexOf(this);
  84988. this._system.lensFlares.splice(index, 1);
  84989. };
  84990. ;
  84991. return LensFlare;
  84992. }());
  84993. BABYLON.LensFlare = LensFlare;
  84994. })(BABYLON || (BABYLON = {}));
  84995. //# sourceMappingURL=babylon.lensFlare.js.map
  84996. var BABYLON;
  84997. (function (BABYLON) {
  84998. // Adds the parser to the scene parsers.
  84999. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  85000. // Lens flares
  85001. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  85002. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  85003. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  85004. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  85005. container.lensFlareSystems.push(lf);
  85006. }
  85007. }
  85008. });
  85009. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  85010. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  85011. if (this.lensFlareSystems[index].name === name) {
  85012. return this.lensFlareSystems[index];
  85013. }
  85014. }
  85015. return null;
  85016. };
  85017. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  85018. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  85019. if (this.lensFlareSystems[index].id === id) {
  85020. return this.lensFlareSystems[index];
  85021. }
  85022. }
  85023. return null;
  85024. };
  85025. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  85026. var index = this.lensFlareSystems.indexOf(toRemove);
  85027. if (index !== -1) {
  85028. this.lensFlareSystems.splice(index, 1);
  85029. }
  85030. return index;
  85031. };
  85032. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  85033. this.lensFlareSystems.push(newLensFlareSystem);
  85034. };
  85035. /**
  85036. * Defines the lens flare scene component responsible to manage any lens flares
  85037. * in a given scene.
  85038. */
  85039. var LensFlareSystemSceneComponent = /** @class */ (function () {
  85040. /**
  85041. * Creates a new instance of the component for the given scene
  85042. * @param scene Defines the scene to register the component in
  85043. */
  85044. function LensFlareSystemSceneComponent(scene) {
  85045. /**
  85046. * The component name helpfull to identify the component in the list of scene components.
  85047. */
  85048. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  85049. this.scene = scene;
  85050. scene.lensFlareSystems = new Array();
  85051. }
  85052. /**
  85053. * Registers the component in a given scene
  85054. */
  85055. LensFlareSystemSceneComponent.prototype.register = function () {
  85056. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  85057. };
  85058. /**
  85059. * Rebuilds the elements related to this component in case of
  85060. * context lost for instance.
  85061. */
  85062. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  85063. // Nothing to do for lens flare
  85064. };
  85065. /**
  85066. * Adds all the element from the container to the scene
  85067. * @param container the container holding the elements
  85068. */
  85069. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  85070. var _this = this;
  85071. if (!container.lensFlareSystems) {
  85072. return;
  85073. }
  85074. container.lensFlareSystems.forEach(function (o) {
  85075. _this.scene.addLensFlareSystem(o);
  85076. });
  85077. };
  85078. /**
  85079. * Removes all the elements in the container from the scene
  85080. * @param container contains the elements to remove
  85081. */
  85082. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  85083. var _this = this;
  85084. if (!container.lensFlareSystems) {
  85085. return;
  85086. }
  85087. container.lensFlareSystems.forEach(function (o) {
  85088. _this.scene.removeLensFlareSystem(o);
  85089. });
  85090. };
  85091. /**
  85092. * Serializes the component data to the specified json object
  85093. * @param serializationObject The object to serialize to
  85094. */
  85095. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  85096. // Lens flares
  85097. serializationObject.lensFlareSystems = [];
  85098. var lensFlareSystems = this.scene.lensFlareSystems;
  85099. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  85100. var lensFlareSystem = lensFlareSystems_1[_i];
  85101. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  85102. }
  85103. };
  85104. /**
  85105. * Disposes the component and the associated ressources.
  85106. */
  85107. LensFlareSystemSceneComponent.prototype.dispose = function () {
  85108. var lensFlareSystems = this.scene.lensFlareSystems;
  85109. while (lensFlareSystems.length) {
  85110. lensFlareSystems[0].dispose();
  85111. }
  85112. };
  85113. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  85114. // Lens flares
  85115. if (this.scene.lensFlaresEnabled) {
  85116. var lensFlareSystems = this.scene.lensFlareSystems;
  85117. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85118. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  85119. var lensFlareSystem = lensFlareSystems_2[_i];
  85120. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  85121. lensFlareSystem.render();
  85122. }
  85123. }
  85124. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85125. }
  85126. };
  85127. return LensFlareSystemSceneComponent;
  85128. }());
  85129. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  85130. })(BABYLON || (BABYLON = {}));
  85131. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  85132. var BABYLON;
  85133. (function (BABYLON) {
  85134. var LensFlareSystem = /** @class */ (function () {
  85135. function LensFlareSystem(name, emitter, scene) {
  85136. this.name = name;
  85137. this.lensFlares = new Array();
  85138. this.borderLimit = 300;
  85139. this.viewportBorder = 0;
  85140. this.layerMask = 0x0FFFFFFF;
  85141. this._vertexBuffers = {};
  85142. this._isEnabled = true;
  85143. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85144. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  85145. if (!component) {
  85146. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  85147. scene._addComponent(component);
  85148. }
  85149. this._emitter = emitter;
  85150. this.id = name;
  85151. scene.lensFlareSystems.push(this);
  85152. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  85153. var engine = scene.getEngine();
  85154. // VBO
  85155. var vertices = [];
  85156. vertices.push(1, 1);
  85157. vertices.push(-1, 1);
  85158. vertices.push(-1, -1);
  85159. vertices.push(1, -1);
  85160. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85161. // Indices
  85162. var indices = [];
  85163. indices.push(0);
  85164. indices.push(1);
  85165. indices.push(2);
  85166. indices.push(0);
  85167. indices.push(2);
  85168. indices.push(3);
  85169. this._indexBuffer = engine.createIndexBuffer(indices);
  85170. // Effects
  85171. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  85172. }
  85173. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  85174. get: function () {
  85175. return this._isEnabled;
  85176. },
  85177. set: function (value) {
  85178. this._isEnabled = value;
  85179. },
  85180. enumerable: true,
  85181. configurable: true
  85182. });
  85183. LensFlareSystem.prototype.getScene = function () {
  85184. return this._scene;
  85185. };
  85186. LensFlareSystem.prototype.getEmitter = function () {
  85187. return this._emitter;
  85188. };
  85189. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  85190. this._emitter = newEmitter;
  85191. };
  85192. LensFlareSystem.prototype.getEmitterPosition = function () {
  85193. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  85194. };
  85195. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  85196. var position = this.getEmitterPosition();
  85197. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  85198. this._positionX = position.x;
  85199. this._positionY = position.y;
  85200. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  85201. if (this.viewportBorder > 0) {
  85202. globalViewport.x -= this.viewportBorder;
  85203. globalViewport.y -= this.viewportBorder;
  85204. globalViewport.width += this.viewportBorder * 2;
  85205. globalViewport.height += this.viewportBorder * 2;
  85206. position.x += this.viewportBorder;
  85207. position.y += this.viewportBorder;
  85208. this._positionX += this.viewportBorder;
  85209. this._positionY += this.viewportBorder;
  85210. }
  85211. if (position.z > 0) {
  85212. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  85213. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  85214. return true;
  85215. }
  85216. return true;
  85217. }
  85218. return false;
  85219. };
  85220. LensFlareSystem.prototype._isVisible = function () {
  85221. if (!this._isEnabled || !this._scene.activeCamera) {
  85222. return false;
  85223. }
  85224. var emitterPosition = this.getEmitterPosition();
  85225. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  85226. var distance = direction.length();
  85227. direction.normalize();
  85228. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  85229. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  85230. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  85231. };
  85232. LensFlareSystem.prototype.render = function () {
  85233. if (!this._effect.isReady() || !this._scene.activeCamera)
  85234. return false;
  85235. var engine = this._scene.getEngine();
  85236. var viewport = this._scene.activeCamera.viewport;
  85237. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  85238. // Position
  85239. if (!this.computeEffectivePosition(globalViewport)) {
  85240. return false;
  85241. }
  85242. // Visibility
  85243. if (!this._isVisible()) {
  85244. return false;
  85245. }
  85246. // Intensity
  85247. var awayX;
  85248. var awayY;
  85249. if (this._positionX < this.borderLimit + globalViewport.x) {
  85250. awayX = this.borderLimit + globalViewport.x - this._positionX;
  85251. }
  85252. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  85253. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  85254. }
  85255. else {
  85256. awayX = 0;
  85257. }
  85258. if (this._positionY < this.borderLimit + globalViewport.y) {
  85259. awayY = this.borderLimit + globalViewport.y - this._positionY;
  85260. }
  85261. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  85262. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  85263. }
  85264. else {
  85265. awayY = 0;
  85266. }
  85267. var away = (awayX > awayY) ? awayX : awayY;
  85268. away -= this.viewportBorder;
  85269. if (away > this.borderLimit) {
  85270. away = this.borderLimit;
  85271. }
  85272. var intensity = 1.0 - (away / this.borderLimit);
  85273. if (intensity < 0) {
  85274. return false;
  85275. }
  85276. if (intensity > 1.0) {
  85277. intensity = 1.0;
  85278. }
  85279. if (this.viewportBorder > 0) {
  85280. globalViewport.x += this.viewportBorder;
  85281. globalViewport.y += this.viewportBorder;
  85282. globalViewport.width -= this.viewportBorder * 2;
  85283. globalViewport.height -= this.viewportBorder * 2;
  85284. this._positionX -= this.viewportBorder;
  85285. this._positionY -= this.viewportBorder;
  85286. }
  85287. // Position
  85288. var centerX = globalViewport.x + globalViewport.width / 2;
  85289. var centerY = globalViewport.y + globalViewport.height / 2;
  85290. var distX = centerX - this._positionX;
  85291. var distY = centerY - this._positionY;
  85292. // Effects
  85293. engine.enableEffect(this._effect);
  85294. engine.setState(false);
  85295. engine.setDepthBuffer(false);
  85296. // VBOs
  85297. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  85298. // Flares
  85299. for (var index = 0; index < this.lensFlares.length; index++) {
  85300. var flare = this.lensFlares[index];
  85301. engine.setAlphaMode(flare.alphaMode);
  85302. var x = centerX - (distX * flare.position);
  85303. var y = centerY - (distY * flare.position);
  85304. var cw = flare.size;
  85305. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  85306. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  85307. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  85308. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  85309. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  85310. // Texture
  85311. this._effect.setTexture("textureSampler", flare.texture);
  85312. // Color
  85313. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  85314. // Draw order
  85315. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85316. }
  85317. engine.setDepthBuffer(true);
  85318. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85319. return true;
  85320. };
  85321. LensFlareSystem.prototype.dispose = function () {
  85322. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85323. if (vertexBuffer) {
  85324. vertexBuffer.dispose();
  85325. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85326. }
  85327. if (this._indexBuffer) {
  85328. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85329. this._indexBuffer = null;
  85330. }
  85331. while (this.lensFlares.length) {
  85332. this.lensFlares[0].dispose();
  85333. }
  85334. // Remove from scene
  85335. var index = this._scene.lensFlareSystems.indexOf(this);
  85336. this._scene.lensFlareSystems.splice(index, 1);
  85337. };
  85338. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  85339. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  85340. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  85341. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  85342. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  85343. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  85344. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  85345. var parsedFlare = parsedLensFlareSystem.flares[index];
  85346. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  85347. }
  85348. return lensFlareSystem;
  85349. };
  85350. LensFlareSystem.prototype.serialize = function () {
  85351. var serializationObject = {};
  85352. serializationObject.id = this.id;
  85353. serializationObject.name = this.name;
  85354. serializationObject.emitterId = this.getEmitter().id;
  85355. serializationObject.borderLimit = this.borderLimit;
  85356. serializationObject.flares = [];
  85357. for (var index = 0; index < this.lensFlares.length; index++) {
  85358. var flare = this.lensFlares[index];
  85359. serializationObject.flares.push({
  85360. size: flare.size,
  85361. position: flare.position,
  85362. color: flare.color.asArray(),
  85363. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  85364. });
  85365. }
  85366. return serializationObject;
  85367. };
  85368. return LensFlareSystem;
  85369. }());
  85370. BABYLON.LensFlareSystem = LensFlareSystem;
  85371. })(BABYLON || (BABYLON = {}));
  85372. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  85373. var BABYLON;
  85374. (function (BABYLON) {
  85375. /**
  85376. * This is a holder class for the physics joint created by the physics plugin.
  85377. * It holds a set of functions to control the underlying joint.
  85378. */
  85379. var PhysicsJoint = /** @class */ (function () {
  85380. function PhysicsJoint(type, jointData) {
  85381. this.type = type;
  85382. this.jointData = jointData;
  85383. jointData.nativeParams = jointData.nativeParams || {};
  85384. }
  85385. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  85386. get: function () {
  85387. return this._physicsJoint;
  85388. },
  85389. set: function (newJoint) {
  85390. if (this._physicsJoint) {
  85391. //remove from the wolrd
  85392. }
  85393. this._physicsJoint = newJoint;
  85394. },
  85395. enumerable: true,
  85396. configurable: true
  85397. });
  85398. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  85399. set: function (physicsPlugin) {
  85400. this._physicsPlugin = physicsPlugin;
  85401. },
  85402. enumerable: true,
  85403. configurable: true
  85404. });
  85405. /**
  85406. * Execute a function that is physics-plugin specific.
  85407. * @param {Function} func the function that will be executed.
  85408. * It accepts two parameters: the physics world and the physics joint.
  85409. */
  85410. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  85411. func(this._physicsPlugin.world, this._physicsJoint);
  85412. };
  85413. //TODO check if the native joints are the same
  85414. //Joint Types
  85415. PhysicsJoint.DistanceJoint = 0;
  85416. PhysicsJoint.HingeJoint = 1;
  85417. PhysicsJoint.BallAndSocketJoint = 2;
  85418. PhysicsJoint.WheelJoint = 3;
  85419. PhysicsJoint.SliderJoint = 4;
  85420. //OIMO
  85421. PhysicsJoint.PrismaticJoint = 5;
  85422. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  85423. PhysicsJoint.UniversalJoint = 6;
  85424. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  85425. //Cannon
  85426. //Similar to a Ball-Joint. Different in params
  85427. PhysicsJoint.PointToPointJoint = 8;
  85428. //Cannon only at the moment
  85429. PhysicsJoint.SpringJoint = 9;
  85430. PhysicsJoint.LockJoint = 10;
  85431. return PhysicsJoint;
  85432. }());
  85433. BABYLON.PhysicsJoint = PhysicsJoint;
  85434. /**
  85435. * A class representing a physics distance joint.
  85436. */
  85437. var DistanceJoint = /** @class */ (function (_super) {
  85438. __extends(DistanceJoint, _super);
  85439. function DistanceJoint(jointData) {
  85440. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  85441. }
  85442. /**
  85443. * Update the predefined distance.
  85444. */
  85445. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  85446. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  85447. };
  85448. return DistanceJoint;
  85449. }(PhysicsJoint));
  85450. BABYLON.DistanceJoint = DistanceJoint;
  85451. var MotorEnabledJoint = /** @class */ (function (_super) {
  85452. __extends(MotorEnabledJoint, _super);
  85453. function MotorEnabledJoint(type, jointData) {
  85454. return _super.call(this, type, jointData) || this;
  85455. }
  85456. /**
  85457. * Set the motor values.
  85458. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85459. * @param {number} force the force to apply
  85460. * @param {number} maxForce max force for this motor.
  85461. */
  85462. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  85463. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85464. };
  85465. /**
  85466. * Set the motor's limits.
  85467. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85468. */
  85469. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85470. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85471. };
  85472. return MotorEnabledJoint;
  85473. }(PhysicsJoint));
  85474. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  85475. /**
  85476. * This class represents a single hinge physics joint
  85477. */
  85478. var HingeJoint = /** @class */ (function (_super) {
  85479. __extends(HingeJoint, _super);
  85480. function HingeJoint(jointData) {
  85481. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  85482. }
  85483. /**
  85484. * Set the motor values.
  85485. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85486. * @param {number} force the force to apply
  85487. * @param {number} maxForce max force for this motor.
  85488. */
  85489. HingeJoint.prototype.setMotor = function (force, maxForce) {
  85490. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85491. };
  85492. /**
  85493. * Set the motor's limits.
  85494. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85495. */
  85496. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85497. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85498. };
  85499. return HingeJoint;
  85500. }(MotorEnabledJoint));
  85501. BABYLON.HingeJoint = HingeJoint;
  85502. /**
  85503. * This class represents a dual hinge physics joint (same as wheel joint)
  85504. */
  85505. var Hinge2Joint = /** @class */ (function (_super) {
  85506. __extends(Hinge2Joint, _super);
  85507. function Hinge2Joint(jointData) {
  85508. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  85509. }
  85510. /**
  85511. * Set the motor values.
  85512. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85513. * @param {number} force the force to apply
  85514. * @param {number} maxForce max force for this motor.
  85515. * @param {motorIndex} the motor's index, 0 or 1.
  85516. */
  85517. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  85518. if (motorIndex === void 0) { motorIndex = 0; }
  85519. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  85520. };
  85521. /**
  85522. * Set the motor limits.
  85523. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85524. * @param {number} upperLimit the upper limit
  85525. * @param {number} lowerLimit lower limit
  85526. * @param {motorIndex} the motor's index, 0 or 1.
  85527. */
  85528. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  85529. if (motorIndex === void 0) { motorIndex = 0; }
  85530. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  85531. };
  85532. return Hinge2Joint;
  85533. }(MotorEnabledJoint));
  85534. BABYLON.Hinge2Joint = Hinge2Joint;
  85535. })(BABYLON || (BABYLON = {}));
  85536. //# sourceMappingURL=babylon.physicsJoint.js.map
  85537. var BABYLON;
  85538. (function (BABYLON) {
  85539. var PhysicsImpostor = /** @class */ (function () {
  85540. function PhysicsImpostor(object, type, _options, _scene) {
  85541. if (_options === void 0) { _options = { mass: 0 }; }
  85542. var _this = this;
  85543. this.object = object;
  85544. this.type = type;
  85545. this._options = _options;
  85546. this._scene = _scene;
  85547. this._bodyUpdateRequired = false;
  85548. this._onBeforePhysicsStepCallbacks = new Array();
  85549. this._onAfterPhysicsStepCallbacks = new Array();
  85550. this._onPhysicsCollideCallbacks = [];
  85551. this._deltaPosition = BABYLON.Vector3.Zero();
  85552. this._isDisposed = false;
  85553. //temp variables for parent rotation calculations
  85554. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  85555. this._tmpQuat = new BABYLON.Quaternion();
  85556. this._tmpQuat2 = new BABYLON.Quaternion();
  85557. /**
  85558. * this function is executed by the physics engine.
  85559. */
  85560. this.beforeStep = function () {
  85561. if (!_this._physicsEngine) {
  85562. return;
  85563. }
  85564. _this.object.translate(_this._deltaPosition, -1);
  85565. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  85566. _this.object.computeWorldMatrix(false);
  85567. if (_this.object.parent && _this.object.rotationQuaternion) {
  85568. _this.getParentsRotation();
  85569. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  85570. }
  85571. else {
  85572. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  85573. }
  85574. if (!_this._options.disableBidirectionalTransformation) {
  85575. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  85576. }
  85577. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  85578. func(_this);
  85579. });
  85580. };
  85581. /**
  85582. * this function is executed by the physics engine.
  85583. */
  85584. this.afterStep = function () {
  85585. if (!_this._physicsEngine) {
  85586. return;
  85587. }
  85588. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  85589. func(_this);
  85590. });
  85591. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  85592. // object has now its world rotation. needs to be converted to local.
  85593. if (_this.object.parent && _this.object.rotationQuaternion) {
  85594. _this.getParentsRotation();
  85595. _this._tmpQuat.conjugateInPlace();
  85596. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  85597. }
  85598. // take the position set and make it the absolute position of this object.
  85599. _this.object.setAbsolutePosition(_this.object.position);
  85600. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  85601. _this.object.translate(_this._deltaPosition, 1);
  85602. };
  85603. /**
  85604. * Legacy collision detection event support
  85605. */
  85606. this.onCollideEvent = null;
  85607. //event and body object due to cannon's event-based architecture.
  85608. this.onCollide = function (e) {
  85609. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  85610. return;
  85611. }
  85612. if (!_this._physicsEngine) {
  85613. return;
  85614. }
  85615. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  85616. if (otherImpostor) {
  85617. // Legacy collision detection event support
  85618. if (_this.onCollideEvent) {
  85619. _this.onCollideEvent(_this, otherImpostor);
  85620. }
  85621. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85622. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85623. }).forEach(function (obj) {
  85624. obj.callback(_this, otherImpostor);
  85625. });
  85626. }
  85627. };
  85628. //sanity check!
  85629. if (!this.object) {
  85630. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85631. return;
  85632. }
  85633. //legacy support for old syntax.
  85634. if (!this._scene && object.getScene) {
  85635. this._scene = object.getScene();
  85636. }
  85637. if (!this._scene) {
  85638. return;
  85639. }
  85640. this._physicsEngine = this._scene.getPhysicsEngine();
  85641. if (!this._physicsEngine) {
  85642. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85643. }
  85644. else {
  85645. //set the object's quaternion, if not set
  85646. if (!this.object.rotationQuaternion) {
  85647. if (this.object.rotation) {
  85648. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85649. }
  85650. else {
  85651. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85652. }
  85653. }
  85654. //default options params
  85655. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85656. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85657. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85658. this._joints = [];
  85659. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85660. if (!this.object.parent || this._options.ignoreParent) {
  85661. this._init();
  85662. }
  85663. else if (this.object.parent.physicsImpostor) {
  85664. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85665. }
  85666. }
  85667. }
  85668. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85669. get: function () {
  85670. return this._isDisposed;
  85671. },
  85672. enumerable: true,
  85673. configurable: true
  85674. });
  85675. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85676. get: function () {
  85677. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85678. },
  85679. set: function (value) {
  85680. this.setMass(value);
  85681. },
  85682. enumerable: true,
  85683. configurable: true
  85684. });
  85685. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85686. get: function () {
  85687. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85688. },
  85689. set: function (value) {
  85690. if (!this._physicsEngine) {
  85691. return;
  85692. }
  85693. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85694. },
  85695. enumerable: true,
  85696. configurable: true
  85697. });
  85698. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85699. get: function () {
  85700. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85701. },
  85702. set: function (value) {
  85703. if (!this._physicsEngine) {
  85704. return;
  85705. }
  85706. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85707. },
  85708. enumerable: true,
  85709. configurable: true
  85710. });
  85711. /**
  85712. * This function will completly initialize this impostor.
  85713. * It will create a new body - but only if this mesh has no parent.
  85714. * If it has, this impostor will not be used other than to define the impostor
  85715. * of the child mesh.
  85716. */
  85717. PhysicsImpostor.prototype._init = function () {
  85718. if (!this._physicsEngine) {
  85719. return;
  85720. }
  85721. this._physicsEngine.removeImpostor(this);
  85722. this.physicsBody = null;
  85723. this._parent = this._parent || this._getPhysicsParent();
  85724. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85725. this._physicsEngine.addImpostor(this);
  85726. }
  85727. };
  85728. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85729. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85730. var parentMesh = this.object.parent;
  85731. return parentMesh.physicsImpostor;
  85732. }
  85733. return null;
  85734. };
  85735. /**
  85736. * Should a new body be generated.
  85737. */
  85738. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85739. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85740. };
  85741. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85742. this.forceUpdate();
  85743. };
  85744. /**
  85745. * Force a regeneration of this or the parent's impostor's body.
  85746. * Use under cautious - This will remove all joints already implemented.
  85747. */
  85748. PhysicsImpostor.prototype.forceUpdate = function () {
  85749. this._init();
  85750. if (this.parent && !this._options.ignoreParent) {
  85751. this.parent.forceUpdate();
  85752. }
  85753. };
  85754. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85755. /*public get mesh(): AbstractMesh {
  85756. return this._mesh;
  85757. }*/
  85758. /**
  85759. * Gets the body that holds this impostor. Either its own, or its parent.
  85760. */
  85761. get: function () {
  85762. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85763. },
  85764. /**
  85765. * Set the physics body. Used mainly by the physics engine/plugin
  85766. */
  85767. set: function (physicsBody) {
  85768. if (this._physicsBody && this._physicsEngine) {
  85769. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85770. }
  85771. this._physicsBody = physicsBody;
  85772. this.resetUpdateFlags();
  85773. },
  85774. enumerable: true,
  85775. configurable: true
  85776. });
  85777. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85778. get: function () {
  85779. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85780. },
  85781. set: function (value) {
  85782. this._parent = value;
  85783. },
  85784. enumerable: true,
  85785. configurable: true
  85786. });
  85787. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85788. this._bodyUpdateRequired = false;
  85789. };
  85790. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85791. if (this.object.getBoundingInfo) {
  85792. var q = this.object.rotationQuaternion;
  85793. //reset rotation
  85794. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85795. //calculate the world matrix with no rotation
  85796. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85797. var boundingInfo = this.object.getBoundingInfo();
  85798. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85799. //bring back the rotation
  85800. this.object.rotationQuaternion = q;
  85801. //calculate the world matrix with the new rotation
  85802. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85803. return size;
  85804. }
  85805. else {
  85806. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85807. }
  85808. };
  85809. PhysicsImpostor.prototype.getObjectCenter = function () {
  85810. if (this.object.getBoundingInfo) {
  85811. var boundingInfo = this.object.getBoundingInfo();
  85812. return boundingInfo.boundingBox.centerWorld;
  85813. }
  85814. else {
  85815. return this.object.position;
  85816. }
  85817. };
  85818. /**
  85819. * Get a specific parametes from the options parameter.
  85820. */
  85821. PhysicsImpostor.prototype.getParam = function (paramName) {
  85822. return this._options[paramName];
  85823. };
  85824. /**
  85825. * Sets a specific parameter in the options given to the physics plugin
  85826. */
  85827. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85828. this._options[paramName] = value;
  85829. this._bodyUpdateRequired = true;
  85830. };
  85831. /**
  85832. * Specifically change the body's mass option. Won't recreate the physics body object
  85833. */
  85834. PhysicsImpostor.prototype.setMass = function (mass) {
  85835. if (this.getParam("mass") !== mass) {
  85836. this.setParam("mass", mass);
  85837. }
  85838. if (this._physicsEngine) {
  85839. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85840. }
  85841. };
  85842. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85843. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85844. };
  85845. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85846. if (this._physicsEngine) {
  85847. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85848. }
  85849. };
  85850. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85851. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85852. };
  85853. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85854. if (this._physicsEngine) {
  85855. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85856. }
  85857. };
  85858. /**
  85859. * Execute a function with the physics plugin native code.
  85860. * Provide a function the will have two variables - the world object and the physics body object.
  85861. */
  85862. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85863. if (this._physicsEngine) {
  85864. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85865. }
  85866. };
  85867. /**
  85868. * Register a function that will be executed before the physics world is stepping forward.
  85869. */
  85870. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85871. this._onBeforePhysicsStepCallbacks.push(func);
  85872. };
  85873. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85874. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85875. if (index > -1) {
  85876. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85877. }
  85878. else {
  85879. BABYLON.Tools.Warn("Function to remove was not found");
  85880. }
  85881. };
  85882. /**
  85883. * Register a function that will be executed after the physics step
  85884. */
  85885. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85886. this._onAfterPhysicsStepCallbacks.push(func);
  85887. };
  85888. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85889. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85890. if (index > -1) {
  85891. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85892. }
  85893. else {
  85894. BABYLON.Tools.Warn("Function to remove was not found");
  85895. }
  85896. };
  85897. /**
  85898. * register a function that will be executed when this impostor collides against a different body.
  85899. */
  85900. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85901. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85902. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85903. };
  85904. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85905. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85906. var index = -1;
  85907. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85908. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85909. // chcek the arrays match
  85910. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85911. return collidedAgainstList.indexOf(impostor) > -1;
  85912. });
  85913. if (sameList) {
  85914. index = idx;
  85915. }
  85916. return sameList;
  85917. }
  85918. return false;
  85919. });
  85920. if (found) {
  85921. this._onPhysicsCollideCallbacks.splice(index, 1);
  85922. }
  85923. else {
  85924. BABYLON.Tools.Warn("Function to remove was not found");
  85925. }
  85926. };
  85927. PhysicsImpostor.prototype.getParentsRotation = function () {
  85928. var parent = this.object.parent;
  85929. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85930. while (parent) {
  85931. if (parent.rotationQuaternion) {
  85932. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85933. }
  85934. else {
  85935. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85936. }
  85937. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85938. parent = parent.parent;
  85939. }
  85940. return this._tmpQuat;
  85941. };
  85942. /**
  85943. * Apply a force
  85944. */
  85945. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85946. if (this._physicsEngine) {
  85947. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85948. }
  85949. return this;
  85950. };
  85951. /**
  85952. * Apply an impulse
  85953. */
  85954. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85955. if (this._physicsEngine) {
  85956. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85957. }
  85958. return this;
  85959. };
  85960. /**
  85961. * A help function to create a joint.
  85962. */
  85963. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85964. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85965. this.addJoint(otherImpostor, joint);
  85966. return this;
  85967. };
  85968. /**
  85969. * Add a joint to this impostor with a different impostor.
  85970. */
  85971. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85972. this._joints.push({
  85973. otherImpostor: otherImpostor,
  85974. joint: joint
  85975. });
  85976. if (this._physicsEngine) {
  85977. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85978. }
  85979. return this;
  85980. };
  85981. /**
  85982. * Will keep this body still, in a sleep mode.
  85983. */
  85984. PhysicsImpostor.prototype.sleep = function () {
  85985. if (this._physicsEngine) {
  85986. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85987. }
  85988. return this;
  85989. };
  85990. /**
  85991. * Wake the body up.
  85992. */
  85993. PhysicsImpostor.prototype.wakeUp = function () {
  85994. if (this._physicsEngine) {
  85995. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85996. }
  85997. return this;
  85998. };
  85999. PhysicsImpostor.prototype.clone = function (newObject) {
  86000. if (!newObject)
  86001. return null;
  86002. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  86003. };
  86004. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  86005. var _this = this;
  86006. //no dispose if no physics engine is available.
  86007. if (!this._physicsEngine) {
  86008. return;
  86009. }
  86010. this._joints.forEach(function (j) {
  86011. if (_this._physicsEngine) {
  86012. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  86013. }
  86014. });
  86015. //dispose the physics body
  86016. this._physicsEngine.removeImpostor(this);
  86017. if (this.parent) {
  86018. this.parent.forceUpdate();
  86019. }
  86020. else {
  86021. /*this._object.getChildMeshes().forEach(function(mesh) {
  86022. if (mesh.physicsImpostor) {
  86023. if (disposeChildren) {
  86024. mesh.physicsImpostor.dispose();
  86025. mesh.physicsImpostor = null;
  86026. }
  86027. }
  86028. })*/
  86029. }
  86030. this._isDisposed = true;
  86031. };
  86032. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  86033. this._deltaPosition.copyFrom(position);
  86034. };
  86035. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  86036. if (!this._deltaRotation) {
  86037. this._deltaRotation = new BABYLON.Quaternion();
  86038. }
  86039. this._deltaRotation.copyFrom(rotation);
  86040. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  86041. };
  86042. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  86043. if (this._physicsEngine) {
  86044. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  86045. }
  86046. return this;
  86047. };
  86048. PhysicsImpostor.prototype.getRadius = function () {
  86049. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  86050. };
  86051. /**
  86052. * Sync a bone with this impostor
  86053. * @param bone The bone to sync to the impostor.
  86054. * @param boneMesh The mesh that the bone is influencing.
  86055. * @param jointPivot The pivot of the joint / bone in local space.
  86056. * @param distToJoint Optional distance from the impostor to the joint.
  86057. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86058. */
  86059. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  86060. var tempVec = PhysicsImpostor._tmpVecs[0];
  86061. var mesh = this.object;
  86062. if (mesh.rotationQuaternion) {
  86063. if (adjustRotation) {
  86064. var tempQuat = PhysicsImpostor._tmpQuat;
  86065. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  86066. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  86067. }
  86068. else {
  86069. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  86070. }
  86071. }
  86072. tempVec.x = 0;
  86073. tempVec.y = 0;
  86074. tempVec.z = 0;
  86075. if (jointPivot) {
  86076. tempVec.x = jointPivot.x;
  86077. tempVec.y = jointPivot.y;
  86078. tempVec.z = jointPivot.z;
  86079. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  86080. if (distToJoint === undefined || distToJoint === null) {
  86081. distToJoint = jointPivot.length();
  86082. }
  86083. tempVec.x *= distToJoint;
  86084. tempVec.y *= distToJoint;
  86085. tempVec.z *= distToJoint;
  86086. }
  86087. if (bone.getParent()) {
  86088. tempVec.addInPlace(mesh.getAbsolutePosition());
  86089. bone.setAbsolutePosition(tempVec, boneMesh);
  86090. }
  86091. else {
  86092. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  86093. boneMesh.position.x -= tempVec.x;
  86094. boneMesh.position.y -= tempVec.y;
  86095. boneMesh.position.z -= tempVec.z;
  86096. }
  86097. };
  86098. /**
  86099. * Sync impostor to a bone
  86100. * @param bone The bone that the impostor will be synced to.
  86101. * @param boneMesh The mesh that the bone is influencing.
  86102. * @param jointPivot The pivot of the joint / bone in local space.
  86103. * @param distToJoint Optional distance from the impostor to the joint.
  86104. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86105. * @param boneAxis Optional vector3 axis the bone is aligned with
  86106. */
  86107. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  86108. var mesh = this.object;
  86109. if (mesh.rotationQuaternion) {
  86110. if (adjustRotation) {
  86111. var tempQuat = PhysicsImpostor._tmpQuat;
  86112. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  86113. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  86114. }
  86115. else {
  86116. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  86117. }
  86118. }
  86119. var pos = PhysicsImpostor._tmpVecs[0];
  86120. var boneDir = PhysicsImpostor._tmpVecs[1];
  86121. if (!boneAxis) {
  86122. boneAxis = PhysicsImpostor._tmpVecs[2];
  86123. boneAxis.x = 0;
  86124. boneAxis.y = 1;
  86125. boneAxis.z = 0;
  86126. }
  86127. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  86128. bone.getAbsolutePositionToRef(boneMesh, pos);
  86129. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  86130. distToJoint = jointPivot.length();
  86131. }
  86132. if (distToJoint !== undefined && distToJoint !== null) {
  86133. pos.x += boneDir.x * distToJoint;
  86134. pos.y += boneDir.y * distToJoint;
  86135. pos.z += boneDir.z * distToJoint;
  86136. }
  86137. mesh.setAbsolutePosition(pos);
  86138. };
  86139. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  86140. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  86141. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86142. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  86143. //Impostor types
  86144. PhysicsImpostor.NoImpostor = 0;
  86145. PhysicsImpostor.SphereImpostor = 1;
  86146. PhysicsImpostor.BoxImpostor = 2;
  86147. PhysicsImpostor.PlaneImpostor = 3;
  86148. PhysicsImpostor.MeshImpostor = 4;
  86149. PhysicsImpostor.CylinderImpostor = 7;
  86150. PhysicsImpostor.ParticleImpostor = 8;
  86151. PhysicsImpostor.HeightmapImpostor = 9;
  86152. return PhysicsImpostor;
  86153. }());
  86154. BABYLON.PhysicsImpostor = PhysicsImpostor;
  86155. })(BABYLON || (BABYLON = {}));
  86156. //# sourceMappingURL=babylon.physicsImpostor.js.map
  86157. var BABYLON;
  86158. (function (BABYLON) {
  86159. var PhysicsEngine = /** @class */ (function () {
  86160. function PhysicsEngine(gravity, _physicsPlugin) {
  86161. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  86162. this._physicsPlugin = _physicsPlugin;
  86163. //new methods and parameters
  86164. this._impostors = [];
  86165. this._joints = [];
  86166. if (!this._physicsPlugin.isSupported()) {
  86167. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  86168. + "Please make sure it is included.");
  86169. }
  86170. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  86171. this.setGravity(gravity);
  86172. this.setTimeStep();
  86173. }
  86174. PhysicsEngine.prototype.setGravity = function (gravity) {
  86175. this.gravity = gravity;
  86176. this._physicsPlugin.setGravity(this.gravity);
  86177. };
  86178. /**
  86179. * Set the time step of the physics engine.
  86180. * default is 1/60.
  86181. * To slow it down, enter 1/600 for example.
  86182. * To speed it up, 1/30
  86183. * @param {number} newTimeStep the new timestep to apply to this world.
  86184. */
  86185. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  86186. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  86187. this._physicsPlugin.setTimeStep(newTimeStep);
  86188. };
  86189. /**
  86190. * Get the time step of the physics engine.
  86191. */
  86192. PhysicsEngine.prototype.getTimeStep = function () {
  86193. return this._physicsPlugin.getTimeStep();
  86194. };
  86195. PhysicsEngine.prototype.dispose = function () {
  86196. this._impostors.forEach(function (impostor) {
  86197. impostor.dispose();
  86198. });
  86199. this._physicsPlugin.dispose();
  86200. };
  86201. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  86202. return this._physicsPlugin.name;
  86203. };
  86204. /**
  86205. * Adding a new impostor for the impostor tracking.
  86206. * This will be done by the impostor itself.
  86207. * @param {PhysicsImpostor} impostor the impostor to add
  86208. */
  86209. PhysicsEngine.prototype.addImpostor = function (impostor) {
  86210. impostor.uniqueId = this._impostors.push(impostor);
  86211. //if no parent, generate the body
  86212. if (!impostor.parent) {
  86213. this._physicsPlugin.generatePhysicsBody(impostor);
  86214. }
  86215. };
  86216. /**
  86217. * Remove an impostor from the engine.
  86218. * This impostor and its mesh will not longer be updated by the physics engine.
  86219. * @param {PhysicsImpostor} impostor the impostor to remove
  86220. */
  86221. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  86222. var index = this._impostors.indexOf(impostor);
  86223. if (index > -1) {
  86224. var removed = this._impostors.splice(index, 1);
  86225. //Is it needed?
  86226. if (removed.length) {
  86227. //this will also remove it from the world.
  86228. removed[0].physicsBody = null;
  86229. }
  86230. }
  86231. };
  86232. /**
  86233. * Add a joint to the physics engine
  86234. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  86235. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  86236. * @param {PhysicsJoint} the joint that will connect both impostors.
  86237. */
  86238. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  86239. var impostorJoint = {
  86240. mainImpostor: mainImpostor,
  86241. connectedImpostor: connectedImpostor,
  86242. joint: joint
  86243. };
  86244. joint.physicsPlugin = this._physicsPlugin;
  86245. this._joints.push(impostorJoint);
  86246. this._physicsPlugin.generateJoint(impostorJoint);
  86247. };
  86248. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  86249. var matchingJoints = this._joints.filter(function (impostorJoint) {
  86250. return (impostorJoint.connectedImpostor === connectedImpostor
  86251. && impostorJoint.joint === joint
  86252. && impostorJoint.mainImpostor === mainImpostor);
  86253. });
  86254. if (matchingJoints.length) {
  86255. this._physicsPlugin.removeJoint(matchingJoints[0]);
  86256. //TODO remove it from the list as well
  86257. }
  86258. };
  86259. /**
  86260. * Called by the scene. no need to call it.
  86261. */
  86262. PhysicsEngine.prototype._step = function (delta) {
  86263. var _this = this;
  86264. //check if any mesh has no body / requires an update
  86265. this._impostors.forEach(function (impostor) {
  86266. if (impostor.isBodyInitRequired()) {
  86267. _this._physicsPlugin.generatePhysicsBody(impostor);
  86268. }
  86269. });
  86270. if (delta > 0.1) {
  86271. delta = 0.1;
  86272. }
  86273. else if (delta <= 0) {
  86274. delta = 1.0 / 60.0;
  86275. }
  86276. this._physicsPlugin.executeStep(delta, this._impostors);
  86277. };
  86278. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  86279. return this._physicsPlugin;
  86280. };
  86281. PhysicsEngine.prototype.getImpostors = function () {
  86282. return this._impostors;
  86283. };
  86284. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  86285. for (var i = 0; i < this._impostors.length; ++i) {
  86286. if (this._impostors[i].object === object) {
  86287. return this._impostors[i];
  86288. }
  86289. }
  86290. return null;
  86291. };
  86292. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  86293. for (var i = 0; i < this._impostors.length; ++i) {
  86294. if (this._impostors[i].physicsBody === body) {
  86295. return this._impostors[i];
  86296. }
  86297. }
  86298. return null;
  86299. };
  86300. // Statics
  86301. PhysicsEngine.Epsilon = 0.001;
  86302. return PhysicsEngine;
  86303. }());
  86304. BABYLON.PhysicsEngine = PhysicsEngine;
  86305. })(BABYLON || (BABYLON = {}));
  86306. //# sourceMappingURL=babylon.physicsEngine.js.map
  86307. var BABYLON;
  86308. (function (BABYLON) {
  86309. var PhysicsHelper = /** @class */ (function () {
  86310. function PhysicsHelper(scene) {
  86311. this._scene = scene;
  86312. this._physicsEngine = this._scene.getPhysicsEngine();
  86313. if (!this._physicsEngine) {
  86314. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  86315. }
  86316. }
  86317. /**
  86318. * @param {Vector3} origin the origin of the explosion
  86319. * @param {number} radius the explosion radius
  86320. * @param {number} strength the explosion strength
  86321. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86322. */
  86323. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  86324. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86325. if (!this._physicsEngine) {
  86326. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  86327. return null;
  86328. }
  86329. var impostors = this._physicsEngine.getImpostors();
  86330. if (impostors.length === 0) {
  86331. return null;
  86332. }
  86333. var event = new PhysicsRadialExplosionEvent(this._scene);
  86334. impostors.forEach(function (impostor) {
  86335. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86336. if (!impostorForceAndContactPoint) {
  86337. return;
  86338. }
  86339. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86340. });
  86341. event.dispose(false);
  86342. return event;
  86343. };
  86344. /**
  86345. * @param {Vector3} origin the origin of the explosion
  86346. * @param {number} radius the explosion radius
  86347. * @param {number} strength the explosion strength
  86348. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86349. */
  86350. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  86351. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86352. if (!this._physicsEngine) {
  86353. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86354. return null;
  86355. }
  86356. var impostors = this._physicsEngine.getImpostors();
  86357. if (impostors.length === 0) {
  86358. return null;
  86359. }
  86360. var event = new PhysicsRadialExplosionEvent(this._scene);
  86361. impostors.forEach(function (impostor) {
  86362. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86363. if (!impostorForceAndContactPoint) {
  86364. return;
  86365. }
  86366. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86367. });
  86368. event.dispose(false);
  86369. return event;
  86370. };
  86371. /**
  86372. * @param {Vector3} origin the origin of the explosion
  86373. * @param {number} radius the explosion radius
  86374. * @param {number} strength the explosion strength
  86375. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86376. */
  86377. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  86378. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86379. if (!this._physicsEngine) {
  86380. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86381. return null;
  86382. }
  86383. var impostors = this._physicsEngine.getImpostors();
  86384. if (impostors.length === 0) {
  86385. return null;
  86386. }
  86387. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  86388. event.dispose(false);
  86389. return event;
  86390. };
  86391. /**
  86392. * @param {Vector3} origin the origin of the updraft
  86393. * @param {number} radius the radius of the updraft
  86394. * @param {number} strength the strength of the updraft
  86395. * @param {number} height the height of the updraft
  86396. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  86397. */
  86398. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  86399. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  86400. if (!this._physicsEngine) {
  86401. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86402. return null;
  86403. }
  86404. if (this._physicsEngine.getImpostors().length === 0) {
  86405. return null;
  86406. }
  86407. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  86408. event.dispose(false);
  86409. return event;
  86410. };
  86411. /**
  86412. * @param {Vector3} origin the of the vortex
  86413. * @param {number} radius the radius of the vortex
  86414. * @param {number} strength the strength of the vortex
  86415. * @param {number} height the height of the vortex
  86416. */
  86417. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  86418. if (!this._physicsEngine) {
  86419. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86420. return null;
  86421. }
  86422. if (this._physicsEngine.getImpostors().length === 0) {
  86423. return null;
  86424. }
  86425. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  86426. event.dispose(false);
  86427. return event;
  86428. };
  86429. return PhysicsHelper;
  86430. }());
  86431. BABYLON.PhysicsHelper = PhysicsHelper;
  86432. /***** Radial explosion *****/
  86433. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  86434. function PhysicsRadialExplosionEvent(scene) {
  86435. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  86436. this._rays = [];
  86437. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  86438. this._scene = scene;
  86439. }
  86440. /**
  86441. * Returns the data related to the radial explosion event (sphere & rays).
  86442. * @returns {PhysicsRadialExplosionEventData}
  86443. */
  86444. PhysicsRadialExplosionEvent.prototype.getData = function () {
  86445. this._dataFetched = true;
  86446. return {
  86447. sphere: this._sphere,
  86448. rays: this._rays,
  86449. };
  86450. };
  86451. /**
  86452. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  86453. * @param impostor
  86454. * @param {Vector3} origin the origin of the explosion
  86455. * @param {number} radius the explosion radius
  86456. * @param {number} strength the explosion strength
  86457. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  86458. * @returns {Nullable<PhysicsForceAndContactPoint>}
  86459. */
  86460. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  86461. if (impostor.mass === 0) {
  86462. return null;
  86463. }
  86464. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  86465. return null;
  86466. }
  86467. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86468. return null;
  86469. }
  86470. var impostorObjectCenter = impostor.getObjectCenter();
  86471. var direction = impostorObjectCenter.subtract(origin);
  86472. var ray = new BABYLON.Ray(origin, direction, radius);
  86473. this._rays.push(ray);
  86474. var hit = ray.intersectsMesh(impostor.object);
  86475. var contactPoint = hit.pickedPoint;
  86476. if (!contactPoint) {
  86477. return null;
  86478. }
  86479. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  86480. if (distanceFromOrigin > radius) {
  86481. return null;
  86482. }
  86483. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  86484. ? strength
  86485. : strength * (1 - (distanceFromOrigin / radius));
  86486. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86487. return { force: force, contactPoint: contactPoint };
  86488. };
  86489. /**
  86490. * Disposes the sphere.
  86491. * @param {bolean} force
  86492. */
  86493. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  86494. var _this = this;
  86495. if (force === void 0) { force = true; }
  86496. if (force) {
  86497. this._sphere.dispose();
  86498. }
  86499. else {
  86500. setTimeout(function () {
  86501. if (!_this._dataFetched) {
  86502. _this._sphere.dispose();
  86503. }
  86504. }, 0);
  86505. }
  86506. };
  86507. /*** Helpers ***/
  86508. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  86509. if (!this._sphere) {
  86510. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  86511. this._sphere.isVisible = false;
  86512. }
  86513. };
  86514. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  86515. var impostorObject = impostor.object;
  86516. this._prepareSphere();
  86517. this._sphere.position = origin;
  86518. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  86519. this._sphere._updateBoundingInfo();
  86520. this._sphere.computeWorldMatrix(true);
  86521. return this._sphere.intersectsMesh(impostorObject, true);
  86522. };
  86523. return PhysicsRadialExplosionEvent;
  86524. }());
  86525. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  86526. /***** Gravitational Field *****/
  86527. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  86528. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  86529. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86530. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86531. this._physicsHelper = physicsHelper;
  86532. this._scene = scene;
  86533. this._origin = origin;
  86534. this._radius = radius;
  86535. this._strength = strength;
  86536. this._falloff = falloff;
  86537. this._tickCallback = this._tick.bind(this);
  86538. }
  86539. /**
  86540. * Returns the data related to the gravitational field event (sphere).
  86541. * @returns {PhysicsGravitationalFieldEventData}
  86542. */
  86543. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  86544. this._dataFetched = true;
  86545. return {
  86546. sphere: this._sphere,
  86547. };
  86548. };
  86549. /**
  86550. * Enables the gravitational field.
  86551. */
  86552. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  86553. this._tickCallback.call(this);
  86554. this._scene.registerBeforeRender(this._tickCallback);
  86555. };
  86556. /**
  86557. * Disables the gravitational field.
  86558. */
  86559. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  86560. this._scene.unregisterBeforeRender(this._tickCallback);
  86561. };
  86562. /**
  86563. * Disposes the sphere.
  86564. * @param {bolean} force
  86565. */
  86566. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  86567. var _this = this;
  86568. if (force === void 0) { force = true; }
  86569. if (force) {
  86570. this._sphere.dispose();
  86571. }
  86572. else {
  86573. setTimeout(function () {
  86574. if (!_this._dataFetched) {
  86575. _this._sphere.dispose();
  86576. }
  86577. }, 0);
  86578. }
  86579. };
  86580. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  86581. // Since the params won't change, we fetch the event only once
  86582. if (this._sphere) {
  86583. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86584. }
  86585. else {
  86586. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86587. if (radialExplosionEvent) {
  86588. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  86589. }
  86590. }
  86591. };
  86592. return PhysicsGravitationalFieldEvent;
  86593. }());
  86594. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  86595. /***** Updraft *****/
  86596. var PhysicsUpdraftEvent = /** @class */ (function () {
  86597. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  86598. this._scene = _scene;
  86599. this._origin = _origin;
  86600. this._radius = _radius;
  86601. this._strength = _strength;
  86602. this._height = _height;
  86603. this._updraftMode = _updraftMode;
  86604. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86605. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  86606. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86607. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86608. this._physicsEngine = this._scene.getPhysicsEngine();
  86609. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86610. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86611. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86612. this._originDirection = this._origin.subtract(this._originTop).normalize();
  86613. }
  86614. this._tickCallback = this._tick.bind(this);
  86615. }
  86616. /**
  86617. * Returns the data related to the updraft event (cylinder).
  86618. * @returns {PhysicsUpdraftEventData}
  86619. */
  86620. PhysicsUpdraftEvent.prototype.getData = function () {
  86621. this._dataFetched = true;
  86622. return {
  86623. cylinder: this._cylinder,
  86624. };
  86625. };
  86626. /**
  86627. * Enables the updraft.
  86628. */
  86629. PhysicsUpdraftEvent.prototype.enable = function () {
  86630. this._tickCallback.call(this);
  86631. this._scene.registerBeforeRender(this._tickCallback);
  86632. };
  86633. /**
  86634. * Disables the cortex.
  86635. */
  86636. PhysicsUpdraftEvent.prototype.disable = function () {
  86637. this._scene.unregisterBeforeRender(this._tickCallback);
  86638. };
  86639. /**
  86640. * Disposes the sphere.
  86641. * @param {bolean} force
  86642. */
  86643. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86644. var _this = this;
  86645. if (force === void 0) { force = true; }
  86646. if (force) {
  86647. this._cylinder.dispose();
  86648. }
  86649. else {
  86650. setTimeout(function () {
  86651. if (!_this._dataFetched) {
  86652. _this._cylinder.dispose();
  86653. }
  86654. }, 0);
  86655. }
  86656. };
  86657. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86658. if (impostor.mass === 0) {
  86659. return null;
  86660. }
  86661. if (!this._intersectsWithCylinder(impostor)) {
  86662. return null;
  86663. }
  86664. var impostorObjectCenter = impostor.getObjectCenter();
  86665. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86666. var direction = this._originDirection;
  86667. }
  86668. else {
  86669. var direction = impostorObjectCenter.subtract(this._originTop);
  86670. }
  86671. var multiplier = this._strength * -1;
  86672. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86673. return { force: force, contactPoint: impostorObjectCenter };
  86674. };
  86675. PhysicsUpdraftEvent.prototype._tick = function () {
  86676. var _this = this;
  86677. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86678. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86679. if (!impostorForceAndContactPoint) {
  86680. return;
  86681. }
  86682. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86683. });
  86684. };
  86685. /*** Helpers ***/
  86686. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86687. if (!this._cylinder) {
  86688. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86689. height: this._height,
  86690. diameter: this._radius * 2,
  86691. }, this._scene);
  86692. this._cylinder.isVisible = false;
  86693. }
  86694. };
  86695. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86696. var impostorObject = impostor.object;
  86697. this._prepareCylinder();
  86698. this._cylinder.position = this._cylinderPosition;
  86699. return this._cylinder.intersectsMesh(impostorObject, true);
  86700. };
  86701. return PhysicsUpdraftEvent;
  86702. }());
  86703. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86704. /***** Vortex *****/
  86705. var PhysicsVortexEvent = /** @class */ (function () {
  86706. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86707. this._scene = _scene;
  86708. this._origin = _origin;
  86709. this._radius = _radius;
  86710. this._strength = _strength;
  86711. this._height = _height;
  86712. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86713. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86714. this._updraftMultiplier = 0.02;
  86715. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86716. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86717. this._physicsEngine = this._scene.getPhysicsEngine();
  86718. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86719. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86720. this._tickCallback = this._tick.bind(this);
  86721. }
  86722. /**
  86723. * Returns the data related to the vortex event (cylinder).
  86724. * @returns {PhysicsVortexEventData}
  86725. */
  86726. PhysicsVortexEvent.prototype.getData = function () {
  86727. this._dataFetched = true;
  86728. return {
  86729. cylinder: this._cylinder,
  86730. };
  86731. };
  86732. /**
  86733. * Enables the vortex.
  86734. */
  86735. PhysicsVortexEvent.prototype.enable = function () {
  86736. this._tickCallback.call(this);
  86737. this._scene.registerBeforeRender(this._tickCallback);
  86738. };
  86739. /**
  86740. * Disables the cortex.
  86741. */
  86742. PhysicsVortexEvent.prototype.disable = function () {
  86743. this._scene.unregisterBeforeRender(this._tickCallback);
  86744. };
  86745. /**
  86746. * Disposes the sphere.
  86747. * @param {bolean} force
  86748. */
  86749. PhysicsVortexEvent.prototype.dispose = function (force) {
  86750. var _this = this;
  86751. if (force === void 0) { force = true; }
  86752. if (force) {
  86753. this._cylinder.dispose();
  86754. }
  86755. else {
  86756. setTimeout(function () {
  86757. if (!_this._dataFetched) {
  86758. _this._cylinder.dispose();
  86759. }
  86760. }, 0);
  86761. }
  86762. };
  86763. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86764. if (impostor.mass === 0) {
  86765. return null;
  86766. }
  86767. if (!this._intersectsWithCylinder(impostor)) {
  86768. return null;
  86769. }
  86770. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86771. return null;
  86772. }
  86773. var impostorObjectCenter = impostor.getObjectCenter();
  86774. 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)
  86775. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86776. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86777. var hit = ray.intersectsMesh(impostor.object);
  86778. var contactPoint = hit.pickedPoint;
  86779. if (!contactPoint) {
  86780. return null;
  86781. }
  86782. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86783. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86784. var directionToOrigin = contactPoint.normalize();
  86785. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86786. directionToOrigin = directionToOrigin.negate();
  86787. }
  86788. // TODO: find a more physically based solution
  86789. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86790. var forceX = directionToOrigin.x * this._strength / 8;
  86791. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86792. var forceZ = directionToOrigin.z * this._strength / 8;
  86793. }
  86794. else {
  86795. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86796. var forceY = this._originTop.y * this._updraftMultiplier;
  86797. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86798. }
  86799. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86800. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86801. return { force: force, contactPoint: impostorObjectCenter };
  86802. };
  86803. PhysicsVortexEvent.prototype._tick = function () {
  86804. var _this = this;
  86805. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86806. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86807. if (!impostorForceAndContactPoint) {
  86808. return;
  86809. }
  86810. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86811. });
  86812. };
  86813. /*** Helpers ***/
  86814. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86815. if (!this._cylinder) {
  86816. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86817. height: this._height,
  86818. diameter: this._radius * 2,
  86819. }, this._scene);
  86820. this._cylinder.isVisible = false;
  86821. }
  86822. };
  86823. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86824. var impostorObject = impostor.object;
  86825. this._prepareCylinder();
  86826. this._cylinder.position = this._cylinderPosition;
  86827. return this._cylinder.intersectsMesh(impostorObject, true);
  86828. };
  86829. return PhysicsVortexEvent;
  86830. }());
  86831. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86832. /***** Enums *****/
  86833. /**
  86834. * The strenght of the force in correspondence to the distance of the affected object
  86835. */
  86836. var PhysicsRadialImpulseFalloff;
  86837. (function (PhysicsRadialImpulseFalloff) {
  86838. /** Defines that impulse is constant in strength across it's whole radius */
  86839. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86840. /** DEfines that impulse gets weaker if it's further from the origin */
  86841. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86842. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86843. /**
  86844. * The strenght of the force in correspondence to the distance of the affected object
  86845. */
  86846. var PhysicsUpdraftMode;
  86847. (function (PhysicsUpdraftMode) {
  86848. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86849. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86850. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86851. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86852. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86853. })(BABYLON || (BABYLON = {}));
  86854. //# sourceMappingURL=babylon.physicsHelper.js.map
  86855. var BABYLON;
  86856. (function (BABYLON) {
  86857. var CannonJSPlugin = /** @class */ (function () {
  86858. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86859. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86860. if (iterations === void 0) { iterations = 10; }
  86861. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86862. this.name = "CannonJSPlugin";
  86863. this._physicsMaterials = new Array();
  86864. this._fixedTimeStep = 1 / 60;
  86865. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86866. this.BJSCANNON = CANNON;
  86867. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86868. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86869. this._tmpPosition = BABYLON.Vector3.Zero();
  86870. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86871. this._tmpUnityRotation = new BABYLON.Quaternion();
  86872. if (!this.isSupported()) {
  86873. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86874. return;
  86875. }
  86876. this._extendNamespace();
  86877. this.world = new this.BJSCANNON.World();
  86878. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86879. this.world.solver.iterations = iterations;
  86880. }
  86881. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86882. this.world.gravity.copy(gravity);
  86883. };
  86884. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86885. this._fixedTimeStep = timeStep;
  86886. };
  86887. CannonJSPlugin.prototype.getTimeStep = function () {
  86888. return this._fixedTimeStep;
  86889. };
  86890. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86891. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86892. };
  86893. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86894. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86895. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86896. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86897. };
  86898. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86899. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86900. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86901. impostor.physicsBody.applyForce(impulse, worldPoint);
  86902. };
  86903. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86904. //parent-child relationship. Does this impostor has a parent impostor?
  86905. if (impostor.parent) {
  86906. if (impostor.physicsBody) {
  86907. this.removePhysicsBody(impostor);
  86908. //TODO is that needed?
  86909. impostor.forceUpdate();
  86910. }
  86911. return;
  86912. }
  86913. //should a new body be created for this impostor?
  86914. if (impostor.isBodyInitRequired()) {
  86915. var shape = this._createShape(impostor);
  86916. //unregister events, if body is being changed
  86917. var oldBody = impostor.physicsBody;
  86918. if (oldBody) {
  86919. this.removePhysicsBody(impostor);
  86920. }
  86921. //create the body and material
  86922. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86923. var bodyCreationObject = {
  86924. mass: impostor.getParam("mass"),
  86925. material: material
  86926. };
  86927. // A simple extend, in case native options were used.
  86928. var nativeOptions = impostor.getParam("nativeOptions");
  86929. for (var key in nativeOptions) {
  86930. if (nativeOptions.hasOwnProperty(key)) {
  86931. bodyCreationObject[key] = nativeOptions[key];
  86932. }
  86933. }
  86934. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86935. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86936. this.world.addEventListener("preStep", impostor.beforeStep);
  86937. this.world.addEventListener("postStep", impostor.afterStep);
  86938. impostor.physicsBody.addShape(shape);
  86939. this.world.add(impostor.physicsBody);
  86940. //try to keep the body moving in the right direction by taking old properties.
  86941. //Should be tested!
  86942. if (oldBody) {
  86943. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86944. impostor.physicsBody[param].copy(oldBody[param]);
  86945. });
  86946. }
  86947. this._processChildMeshes(impostor);
  86948. }
  86949. //now update the body's transformation
  86950. this._updatePhysicsBodyTransformation(impostor);
  86951. };
  86952. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86953. var _this = this;
  86954. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86955. var currentRotation = mainImpostor.object.rotationQuaternion;
  86956. if (meshChildren.length) {
  86957. var processMesh = function (localPosition, mesh) {
  86958. if (!currentRotation || !mesh.rotationQuaternion) {
  86959. return;
  86960. }
  86961. var childImpostor = mesh.getPhysicsImpostor();
  86962. if (childImpostor) {
  86963. var parent = childImpostor.parent;
  86964. if (parent !== mainImpostor) {
  86965. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86966. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86967. if (childImpostor.physicsBody) {
  86968. _this.removePhysicsBody(childImpostor);
  86969. childImpostor.physicsBody = null;
  86970. }
  86971. childImpostor.parent = mainImpostor;
  86972. childImpostor.resetUpdateFlags();
  86973. 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));
  86974. //Add the mass of the children.
  86975. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86976. }
  86977. }
  86978. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86979. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86980. };
  86981. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86982. }
  86983. };
  86984. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86985. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86986. this.world.removeEventListener("preStep", impostor.beforeStep);
  86987. this.world.removeEventListener("postStep", impostor.afterStep);
  86988. this.world.remove(impostor.physicsBody);
  86989. };
  86990. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86991. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86992. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86993. if (!mainBody || !connectedBody) {
  86994. return;
  86995. }
  86996. var constraint;
  86997. var jointData = impostorJoint.joint.jointData;
  86998. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86999. var constraintData = {
  87000. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  87001. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  87002. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  87003. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  87004. maxForce: jointData.nativeParams.maxForce,
  87005. collideConnected: !!jointData.collision
  87006. };
  87007. switch (impostorJoint.joint.type) {
  87008. case BABYLON.PhysicsJoint.HingeJoint:
  87009. case BABYLON.PhysicsJoint.Hinge2Joint:
  87010. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  87011. break;
  87012. case BABYLON.PhysicsJoint.DistanceJoint:
  87013. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  87014. break;
  87015. case BABYLON.PhysicsJoint.SpringJoint:
  87016. var springData = jointData;
  87017. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  87018. restLength: springData.length,
  87019. stiffness: springData.stiffness,
  87020. damping: springData.damping,
  87021. localAnchorA: constraintData.pivotA,
  87022. localAnchorB: constraintData.pivotB
  87023. });
  87024. break;
  87025. case BABYLON.PhysicsJoint.LockJoint:
  87026. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  87027. break;
  87028. case BABYLON.PhysicsJoint.PointToPointJoint:
  87029. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87030. default:
  87031. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  87032. break;
  87033. }
  87034. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  87035. constraint.collideConnected = !!jointData.collision;
  87036. impostorJoint.joint.physicsJoint = constraint;
  87037. //don't add spring as constraint, as it is not one.
  87038. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  87039. this.world.addConstraint(constraint);
  87040. }
  87041. else {
  87042. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  87043. constraint.applyForce();
  87044. });
  87045. }
  87046. };
  87047. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87048. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  87049. };
  87050. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  87051. var index;
  87052. var mat;
  87053. for (index = 0; index < this._physicsMaterials.length; index++) {
  87054. mat = this._physicsMaterials[index];
  87055. if (mat.friction === friction && mat.restitution === restitution) {
  87056. return mat;
  87057. }
  87058. }
  87059. var currentMat = new this.BJSCANNON.Material(name);
  87060. currentMat.friction = friction;
  87061. currentMat.restitution = restitution;
  87062. this._physicsMaterials.push(currentMat);
  87063. return currentMat;
  87064. };
  87065. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  87066. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  87067. };
  87068. CannonJSPlugin.prototype._createShape = function (impostor) {
  87069. var object = impostor.object;
  87070. var returnValue;
  87071. var extendSize = impostor.getObjectExtendSize();
  87072. switch (impostor.type) {
  87073. case BABYLON.PhysicsImpostor.SphereImpostor:
  87074. var radiusX = extendSize.x;
  87075. var radiusY = extendSize.y;
  87076. var radiusZ = extendSize.z;
  87077. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  87078. break;
  87079. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  87080. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87081. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  87082. break;
  87083. case BABYLON.PhysicsImpostor.BoxImpostor:
  87084. var box = extendSize.scale(0.5);
  87085. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  87086. break;
  87087. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87088. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  87089. returnValue = new this.BJSCANNON.Plane();
  87090. break;
  87091. case BABYLON.PhysicsImpostor.MeshImpostor:
  87092. // should transform the vertex data to world coordinates!!
  87093. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  87094. var rawFaces = object.getIndices ? object.getIndices() : [];
  87095. if (!rawVerts)
  87096. return;
  87097. // get only scale! so the object could transform correctly.
  87098. var oldPosition = object.position.clone();
  87099. var oldRotation = object.rotation && object.rotation.clone();
  87100. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  87101. object.position.copyFromFloats(0, 0, 0);
  87102. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87103. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87104. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87105. var transform = object.computeWorldMatrix(true);
  87106. // convert rawVerts to object space
  87107. var temp = new Array();
  87108. var index;
  87109. for (index = 0; index < rawVerts.length; index += 3) {
  87110. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  87111. }
  87112. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  87113. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  87114. //now set back the transformation!
  87115. object.position.copyFrom(oldPosition);
  87116. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  87117. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  87118. break;
  87119. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  87120. var oldPosition2 = object.position.clone();
  87121. var oldRotation2 = object.rotation && object.rotation.clone();
  87122. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  87123. object.position.copyFromFloats(0, 0, 0);
  87124. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87125. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87126. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87127. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  87128. returnValue = this._createHeightmap(object);
  87129. object.position.copyFrom(oldPosition2);
  87130. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  87131. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  87132. object.computeWorldMatrix(true);
  87133. break;
  87134. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87135. returnValue = new this.BJSCANNON.Particle();
  87136. break;
  87137. }
  87138. return returnValue;
  87139. };
  87140. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  87141. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87142. var transform = object.computeWorldMatrix(true);
  87143. // convert rawVerts to object space
  87144. var temp = new Array();
  87145. var index;
  87146. for (index = 0; index < pos.length; index += 3) {
  87147. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  87148. }
  87149. pos = temp;
  87150. var matrix = new Array();
  87151. //For now pointDepth will not be used and will be automatically calculated.
  87152. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  87153. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  87154. var boundingInfo = object.getBoundingInfo();
  87155. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  87156. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  87157. var elementSize = dim * 2 / arraySize;
  87158. for (var i = 0; i < pos.length; i = i + 3) {
  87159. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  87160. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  87161. var y = -pos[i + 2] + minY;
  87162. if (!matrix[x]) {
  87163. matrix[x] = [];
  87164. }
  87165. if (!matrix[x][z]) {
  87166. matrix[x][z] = y;
  87167. }
  87168. matrix[x][z] = Math.max(y, matrix[x][z]);
  87169. }
  87170. for (var x = 0; x <= arraySize; ++x) {
  87171. if (!matrix[x]) {
  87172. var loc = 1;
  87173. while (!matrix[(x + loc) % arraySize]) {
  87174. loc++;
  87175. }
  87176. matrix[x] = matrix[(x + loc) % arraySize].slice();
  87177. //console.log("missing x", x);
  87178. }
  87179. for (var z = 0; z <= arraySize; ++z) {
  87180. if (!matrix[x][z]) {
  87181. var loc = 1;
  87182. var newValue;
  87183. while (newValue === undefined) {
  87184. newValue = matrix[x][(z + loc++) % arraySize];
  87185. }
  87186. matrix[x][z] = newValue;
  87187. }
  87188. }
  87189. }
  87190. var shape = new this.BJSCANNON.Heightfield(matrix, {
  87191. elementSize: elementSize
  87192. });
  87193. //For future reference, needed for body transformation
  87194. shape.minY = minY;
  87195. return shape;
  87196. };
  87197. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  87198. var object = impostor.object;
  87199. //make sure it is updated...
  87200. object.computeWorldMatrix && object.computeWorldMatrix(true);
  87201. // The delta between the mesh position and the mesh bounding box center
  87202. var bInfo = object.getBoundingInfo();
  87203. if (!bInfo)
  87204. return;
  87205. var center = impostor.getObjectCenter();
  87206. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  87207. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  87208. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  87209. this._tmpPosition.copyFrom(center);
  87210. var quaternion = object.rotationQuaternion;
  87211. if (!quaternion) {
  87212. return;
  87213. }
  87214. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  87215. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  87216. //-90 DEG in X, precalculated
  87217. quaternion = quaternion.multiply(this._minus90X);
  87218. //Invert! (Precalculated, 90 deg in X)
  87219. //No need to clone. this will never change.
  87220. impostor.setDeltaRotation(this._plus90X);
  87221. }
  87222. //If it is a heightfield, if should be centered.
  87223. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  87224. var mesh = object;
  87225. var boundingInfo = mesh.getBoundingInfo();
  87226. //calculate the correct body position:
  87227. var rotationQuaternion = mesh.rotationQuaternion;
  87228. mesh.rotationQuaternion = this._tmpUnityRotation;
  87229. mesh.computeWorldMatrix(true);
  87230. //get original center with no rotation
  87231. var c = center.clone();
  87232. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  87233. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  87234. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  87235. mesh.setPreTransformMatrix(p);
  87236. mesh.computeWorldMatrix(true);
  87237. //calculate the translation
  87238. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  87239. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  87240. //add it inverted to the delta
  87241. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  87242. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  87243. //rotation is back
  87244. mesh.rotationQuaternion = rotationQuaternion;
  87245. mesh.setPreTransformMatrix(oldPivot);
  87246. mesh.computeWorldMatrix(true);
  87247. }
  87248. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  87249. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  87250. //this._tmpPosition.copyFrom(object.position);
  87251. }
  87252. impostor.setDeltaPosition(this._tmpDeltaPosition);
  87253. //Now update the impostor object
  87254. impostor.physicsBody.position.copy(this._tmpPosition);
  87255. impostor.physicsBody.quaternion.copy(quaternion);
  87256. };
  87257. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87258. impostor.object.position.copyFrom(impostor.physicsBody.position);
  87259. if (impostor.object.rotationQuaternion) {
  87260. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  87261. }
  87262. };
  87263. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87264. impostor.physicsBody.position.copy(newPosition);
  87265. impostor.physicsBody.quaternion.copy(newRotation);
  87266. };
  87267. CannonJSPlugin.prototype.isSupported = function () {
  87268. return this.BJSCANNON !== undefined;
  87269. };
  87270. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87271. impostor.physicsBody.velocity.copy(velocity);
  87272. };
  87273. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87274. impostor.physicsBody.angularVelocity.copy(velocity);
  87275. };
  87276. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87277. var v = impostor.physicsBody.velocity;
  87278. if (!v) {
  87279. return null;
  87280. }
  87281. return new BABYLON.Vector3(v.x, v.y, v.z);
  87282. };
  87283. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87284. var v = impostor.physicsBody.angularVelocity;
  87285. if (!v) {
  87286. return null;
  87287. }
  87288. return new BABYLON.Vector3(v.x, v.y, v.z);
  87289. };
  87290. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87291. impostor.physicsBody.mass = mass;
  87292. impostor.physicsBody.updateMassProperties();
  87293. };
  87294. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  87295. return impostor.physicsBody.mass;
  87296. };
  87297. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  87298. return impostor.physicsBody.material.friction;
  87299. };
  87300. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87301. impostor.physicsBody.material.friction = friction;
  87302. };
  87303. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87304. return impostor.physicsBody.material.restitution;
  87305. };
  87306. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87307. impostor.physicsBody.material.restitution = restitution;
  87308. };
  87309. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  87310. impostor.physicsBody.sleep();
  87311. };
  87312. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  87313. impostor.physicsBody.wakeUp();
  87314. };
  87315. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87316. joint.physicsJoint.distance = maxDistance;
  87317. };
  87318. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87319. // if (!motorIndex) {
  87320. // joint.physicsJoint.enableMotor();
  87321. // }
  87322. // }
  87323. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87324. // if (!motorIndex) {
  87325. // joint.physicsJoint.disableMotor();
  87326. // }
  87327. // }
  87328. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87329. if (!motorIndex) {
  87330. joint.physicsJoint.enableMotor();
  87331. joint.physicsJoint.setMotorSpeed(speed);
  87332. if (maxForce) {
  87333. this.setLimit(joint, maxForce);
  87334. }
  87335. }
  87336. };
  87337. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  87338. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  87339. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  87340. };
  87341. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87342. var body = impostor.physicsBody;
  87343. mesh.position.x = body.position.x;
  87344. mesh.position.y = body.position.y;
  87345. mesh.position.z = body.position.z;
  87346. if (mesh.rotationQuaternion) {
  87347. mesh.rotationQuaternion.x = body.quaternion.x;
  87348. mesh.rotationQuaternion.y = body.quaternion.y;
  87349. mesh.rotationQuaternion.z = body.quaternion.z;
  87350. mesh.rotationQuaternion.w = body.quaternion.w;
  87351. }
  87352. };
  87353. CannonJSPlugin.prototype.getRadius = function (impostor) {
  87354. var shape = impostor.physicsBody.shapes[0];
  87355. return shape.boundingSphereRadius;
  87356. };
  87357. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87358. var shape = impostor.physicsBody.shapes[0];
  87359. result.x = shape.halfExtents.x * 2;
  87360. result.y = shape.halfExtents.y * 2;
  87361. result.z = shape.halfExtents.z * 2;
  87362. };
  87363. CannonJSPlugin.prototype.dispose = function () {
  87364. };
  87365. CannonJSPlugin.prototype._extendNamespace = function () {
  87366. //this will force cannon to execute at least one step when using interpolation
  87367. var step_tmp1 = new this.BJSCANNON.Vec3();
  87368. var Engine = this.BJSCANNON;
  87369. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  87370. maxSubSteps = maxSubSteps || 10;
  87371. timeSinceLastCalled = timeSinceLastCalled || 0;
  87372. if (timeSinceLastCalled === 0) {
  87373. this.internalStep(dt);
  87374. this.time += dt;
  87375. }
  87376. else {
  87377. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  87378. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  87379. var t0 = performance.now();
  87380. for (var i = 0; i !== internalSteps; i++) {
  87381. this.internalStep(dt);
  87382. if (performance.now() - t0 > dt * 1000) {
  87383. break;
  87384. }
  87385. }
  87386. this.time += timeSinceLastCalled;
  87387. var h = this.time % dt;
  87388. var h_div_dt = h / dt;
  87389. var interpvelo = step_tmp1;
  87390. var bodies = this.bodies;
  87391. for (var j = 0; j !== bodies.length; j++) {
  87392. var b = bodies[j];
  87393. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  87394. b.position.vsub(b.previousPosition, interpvelo);
  87395. interpvelo.scale(h_div_dt, interpvelo);
  87396. b.position.vadd(interpvelo, b.interpolatedPosition);
  87397. }
  87398. else {
  87399. b.interpolatedPosition.copy(b.position);
  87400. b.interpolatedQuaternion.copy(b.quaternion);
  87401. }
  87402. }
  87403. }
  87404. };
  87405. };
  87406. return CannonJSPlugin;
  87407. }());
  87408. BABYLON.CannonJSPlugin = CannonJSPlugin;
  87409. })(BABYLON || (BABYLON = {}));
  87410. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  87411. var BABYLON;
  87412. (function (BABYLON) {
  87413. var OimoJSPlugin = /** @class */ (function () {
  87414. function OimoJSPlugin(iterations) {
  87415. this.name = "OimoJSPlugin";
  87416. this._tmpImpostorsArray = [];
  87417. this._tmpPositionVector = BABYLON.Vector3.Zero();
  87418. this.BJSOIMO = OIMO;
  87419. this.world = new this.BJSOIMO.World({
  87420. iterations: iterations
  87421. });
  87422. this.world.clear();
  87423. }
  87424. OimoJSPlugin.prototype.setGravity = function (gravity) {
  87425. this.world.gravity.copy(gravity);
  87426. };
  87427. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  87428. this.world.timeStep = timeStep;
  87429. };
  87430. OimoJSPlugin.prototype.getTimeStep = function () {
  87431. return this.world.timeStep;
  87432. };
  87433. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  87434. var _this = this;
  87435. impostors.forEach(function (impostor) {
  87436. impostor.beforeStep();
  87437. });
  87438. this.world.step();
  87439. impostors.forEach(function (impostor) {
  87440. impostor.afterStep();
  87441. //update the ordered impostors array
  87442. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  87443. });
  87444. //check for collisions
  87445. var contact = this.world.contacts;
  87446. while (contact !== null) {
  87447. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  87448. contact = contact.next;
  87449. continue;
  87450. }
  87451. //is this body colliding with any other? get the impostor
  87452. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  87453. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  87454. if (!mainImpostor || !collidingImpostor) {
  87455. contact = contact.next;
  87456. continue;
  87457. }
  87458. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  87459. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  87460. contact = contact.next;
  87461. }
  87462. };
  87463. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87464. var mass = impostor.physicsBody.mass;
  87465. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  87466. };
  87467. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87468. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  87469. this.applyImpulse(impostor, force, contactPoint);
  87470. };
  87471. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87472. var _this = this;
  87473. //parent-child relationship. Does this impostor has a parent impostor?
  87474. if (impostor.parent) {
  87475. if (impostor.physicsBody) {
  87476. this.removePhysicsBody(impostor);
  87477. //TODO is that needed?
  87478. impostor.forceUpdate();
  87479. }
  87480. return;
  87481. }
  87482. if (impostor.isBodyInitRequired()) {
  87483. var bodyConfig = {
  87484. name: impostor.uniqueId,
  87485. //Oimo must have mass, also for static objects.
  87486. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  87487. size: [],
  87488. type: [],
  87489. pos: [],
  87490. posShape: [],
  87491. rot: [],
  87492. rotShape: [],
  87493. move: impostor.getParam("mass") !== 0,
  87494. density: impostor.getParam("mass"),
  87495. friction: impostor.getParam("friction"),
  87496. restitution: impostor.getParam("restitution"),
  87497. //Supporting older versions of Oimo
  87498. world: this.world
  87499. };
  87500. var impostors = [impostor];
  87501. var addToArray = function (parent) {
  87502. if (!parent.getChildMeshes)
  87503. return;
  87504. parent.getChildMeshes().forEach(function (m) {
  87505. if (m.physicsImpostor) {
  87506. impostors.push(m.physicsImpostor);
  87507. //m.physicsImpostor._init();
  87508. }
  87509. });
  87510. };
  87511. addToArray(impostor.object);
  87512. var checkWithEpsilon_1 = function (value) {
  87513. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  87514. };
  87515. var globalQuaternion_1 = new BABYLON.Quaternion();
  87516. impostors.forEach(function (i) {
  87517. if (!i.object.rotationQuaternion) {
  87518. return;
  87519. }
  87520. //get the correct bounding box
  87521. var oldQuaternion = i.object.rotationQuaternion;
  87522. globalQuaternion_1 = oldQuaternion.clone();
  87523. var rot = oldQuaternion.toEulerAngles();
  87524. var extendSize = i.getObjectExtendSize();
  87525. var radToDeg = 57.295779513082320876;
  87526. if (i === impostor) {
  87527. var center = impostor.getObjectCenter();
  87528. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  87529. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  87530. //Can also use Array.prototype.push.apply
  87531. bodyConfig.pos.push(center.x);
  87532. bodyConfig.pos.push(center.y);
  87533. bodyConfig.pos.push(center.z);
  87534. bodyConfig.posShape.push(0, 0, 0);
  87535. //tmp solution
  87536. bodyConfig.rot.push(0);
  87537. bodyConfig.rot.push(0);
  87538. bodyConfig.rot.push(0);
  87539. bodyConfig.rotShape.push(0, 0, 0);
  87540. }
  87541. else {
  87542. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  87543. bodyConfig.posShape.push(localPosition.x);
  87544. bodyConfig.posShape.push(localPosition.y);
  87545. bodyConfig.posShape.push(localPosition.z);
  87546. bodyConfig.pos.push(0, 0, 0);
  87547. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  87548. bodyConfig.rot.push(0);
  87549. bodyConfig.rot.push(0);
  87550. bodyConfig.rot.push(0);
  87551. bodyConfig.rotShape.push(rot.x * radToDeg);
  87552. bodyConfig.rotShape.push(rot.y * radToDeg);
  87553. bodyConfig.rotShape.push(rot.z * radToDeg);
  87554. }
  87555. // register mesh
  87556. switch (i.type) {
  87557. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87558. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  87559. case BABYLON.PhysicsImpostor.SphereImpostor:
  87560. var radiusX = extendSize.x;
  87561. var radiusY = extendSize.y;
  87562. var radiusZ = extendSize.z;
  87563. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  87564. bodyConfig.type.push('sphere');
  87565. //due to the way oimo works with compounds, add 3 times
  87566. bodyConfig.size.push(size);
  87567. bodyConfig.size.push(size);
  87568. bodyConfig.size.push(size);
  87569. break;
  87570. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87571. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  87572. var sizeY = checkWithEpsilon_1(extendSize.y);
  87573. bodyConfig.type.push('cylinder');
  87574. bodyConfig.size.push(sizeX);
  87575. bodyConfig.size.push(sizeY);
  87576. //due to the way oimo works with compounds, add one more value.
  87577. bodyConfig.size.push(sizeY);
  87578. break;
  87579. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87580. case BABYLON.PhysicsImpostor.BoxImpostor:
  87581. default:
  87582. var sizeX = checkWithEpsilon_1(extendSize.x);
  87583. var sizeY = checkWithEpsilon_1(extendSize.y);
  87584. var sizeZ = checkWithEpsilon_1(extendSize.z);
  87585. bodyConfig.type.push('box');
  87586. //if (i === impostor) {
  87587. bodyConfig.size.push(sizeX);
  87588. bodyConfig.size.push(sizeY);
  87589. bodyConfig.size.push(sizeZ);
  87590. //} else {
  87591. // bodyConfig.size.push(0,0,0);
  87592. //}
  87593. break;
  87594. }
  87595. //actually not needed, but hey...
  87596. i.object.rotationQuaternion = oldQuaternion;
  87597. });
  87598. impostor.physicsBody = this.world.add(bodyConfig);
  87599. // set the quaternion, ignoring the previously defined (euler) rotation
  87600. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  87601. // update with delta 0, so the body will reveive the new rotation.
  87602. impostor.physicsBody.updatePosition(0);
  87603. }
  87604. else {
  87605. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  87606. }
  87607. impostor.setDeltaPosition(this._tmpPositionVector);
  87608. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  87609. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  87610. };
  87611. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87612. //impostor.physicsBody.dispose();
  87613. //Same as : (older oimo versions)
  87614. this.world.removeRigidBody(impostor.physicsBody);
  87615. };
  87616. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87617. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87618. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87619. if (!mainBody || !connectedBody) {
  87620. return;
  87621. }
  87622. var jointData = impostorJoint.joint.jointData;
  87623. var options = jointData.nativeParams || {};
  87624. var type;
  87625. var nativeJointData = {
  87626. body1: mainBody,
  87627. body2: connectedBody,
  87628. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87629. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87630. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87631. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87632. min: options.min,
  87633. max: options.max,
  87634. collision: options.collision || jointData.collision,
  87635. spring: options.spring,
  87636. //supporting older version of Oimo
  87637. world: this.world
  87638. };
  87639. switch (impostorJoint.joint.type) {
  87640. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87641. type = "jointBall";
  87642. break;
  87643. case BABYLON.PhysicsJoint.SpringJoint:
  87644. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87645. var springData = jointData;
  87646. nativeJointData.min = springData.length || nativeJointData.min;
  87647. //Max should also be set, just make sure it is at least min
  87648. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87649. case BABYLON.PhysicsJoint.DistanceJoint:
  87650. type = "jointDistance";
  87651. nativeJointData.max = jointData.maxDistance;
  87652. break;
  87653. case BABYLON.PhysicsJoint.PrismaticJoint:
  87654. type = "jointPrisme";
  87655. break;
  87656. case BABYLON.PhysicsJoint.SliderJoint:
  87657. type = "jointSlide";
  87658. break;
  87659. case BABYLON.PhysicsJoint.WheelJoint:
  87660. type = "jointWheel";
  87661. break;
  87662. case BABYLON.PhysicsJoint.HingeJoint:
  87663. default:
  87664. type = "jointHinge";
  87665. break;
  87666. }
  87667. nativeJointData.type = type;
  87668. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87669. };
  87670. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87671. //Bug in Oimo prevents us from disposing a joint in the playground
  87672. //joint.joint.physicsJoint.dispose();
  87673. //So we will bruteforce it!
  87674. try {
  87675. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87676. }
  87677. catch (e) {
  87678. BABYLON.Tools.Warn(e);
  87679. }
  87680. };
  87681. OimoJSPlugin.prototype.isSupported = function () {
  87682. return this.BJSOIMO !== undefined;
  87683. };
  87684. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87685. if (!impostor.physicsBody.sleeping) {
  87686. //TODO check that
  87687. /*if (impostor.physicsBody.shapes.next) {
  87688. var parentShape = this._getLastShape(impostor.physicsBody);
  87689. impostor.object.position.copyFrom(parentShape.position);
  87690. console.log(parentShape.position);
  87691. } else {*/
  87692. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87693. //}
  87694. if (impostor.object.rotationQuaternion) {
  87695. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87696. }
  87697. }
  87698. };
  87699. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87700. var body = impostor.physicsBody;
  87701. body.position.copy(newPosition);
  87702. body.orientation.copy(newRotation);
  87703. body.syncShapes();
  87704. body.awake();
  87705. };
  87706. /*private _getLastShape(body: any): any {
  87707. var lastShape = body.shapes;
  87708. while (lastShape.next) {
  87709. lastShape = lastShape.next;
  87710. }
  87711. return lastShape;
  87712. }*/
  87713. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87714. impostor.physicsBody.linearVelocity.copy(velocity);
  87715. };
  87716. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87717. impostor.physicsBody.angularVelocity.copy(velocity);
  87718. };
  87719. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87720. var v = impostor.physicsBody.linearVelocity;
  87721. if (!v) {
  87722. return null;
  87723. }
  87724. return new BABYLON.Vector3(v.x, v.y, v.z);
  87725. };
  87726. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87727. var v = impostor.physicsBody.angularVelocity;
  87728. if (!v) {
  87729. return null;
  87730. }
  87731. return new BABYLON.Vector3(v.x, v.y, v.z);
  87732. };
  87733. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87734. var staticBody = mass === 0;
  87735. //this will actually set the body's density and not its mass.
  87736. //But this is how oimo treats the mass variable.
  87737. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87738. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87739. };
  87740. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87741. return impostor.physicsBody.shapes.density;
  87742. };
  87743. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87744. return impostor.physicsBody.shapes.friction;
  87745. };
  87746. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87747. impostor.physicsBody.shapes.friction = friction;
  87748. };
  87749. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87750. return impostor.physicsBody.shapes.restitution;
  87751. };
  87752. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87753. impostor.physicsBody.shapes.restitution = restitution;
  87754. };
  87755. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87756. impostor.physicsBody.sleep();
  87757. };
  87758. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87759. impostor.physicsBody.awake();
  87760. };
  87761. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87762. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87763. if (minDistance !== void 0) {
  87764. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87765. }
  87766. };
  87767. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87768. //TODO separate rotational and transational motors.
  87769. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87770. if (motor) {
  87771. motor.setMotor(speed, maxForce);
  87772. }
  87773. };
  87774. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87775. //TODO separate rotational and transational motors.
  87776. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87777. if (motor) {
  87778. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87779. }
  87780. };
  87781. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87782. var body = impostor.physicsBody;
  87783. mesh.position.x = body.position.x;
  87784. mesh.position.y = body.position.y;
  87785. mesh.position.z = body.position.z;
  87786. if (mesh.rotationQuaternion) {
  87787. mesh.rotationQuaternion.x = body.orientation.x;
  87788. mesh.rotationQuaternion.y = body.orientation.y;
  87789. mesh.rotationQuaternion.z = body.orientation.z;
  87790. mesh.rotationQuaternion.w = body.orientation.s;
  87791. }
  87792. };
  87793. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87794. return impostor.physicsBody.shapes.radius;
  87795. };
  87796. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87797. var shape = impostor.physicsBody.shapes;
  87798. result.x = shape.halfWidth * 2;
  87799. result.y = shape.halfHeight * 2;
  87800. result.z = shape.halfDepth * 2;
  87801. };
  87802. OimoJSPlugin.prototype.dispose = function () {
  87803. this.world.clear();
  87804. };
  87805. return OimoJSPlugin;
  87806. }());
  87807. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87808. })(BABYLON || (BABYLON = {}));
  87809. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87810. var BABYLON;
  87811. (function (BABYLON) {
  87812. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87813. // All values and structures referenced from:
  87814. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87815. var DDS_MAGIC = 0x20534444;
  87816. var
  87817. //DDSD_CAPS = 0x1,
  87818. //DDSD_HEIGHT = 0x2,
  87819. //DDSD_WIDTH = 0x4,
  87820. //DDSD_PITCH = 0x8,
  87821. //DDSD_PIXELFORMAT = 0x1000,
  87822. DDSD_MIPMAPCOUNT = 0x20000;
  87823. //DDSD_LINEARSIZE = 0x80000,
  87824. //DDSD_DEPTH = 0x800000;
  87825. // var DDSCAPS_COMPLEX = 0x8,
  87826. // DDSCAPS_MIPMAP = 0x400000,
  87827. // DDSCAPS_TEXTURE = 0x1000;
  87828. var DDSCAPS2_CUBEMAP = 0x200;
  87829. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87830. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87831. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87832. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87833. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87834. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87835. // DDSCAPS2_VOLUME = 0x200000;
  87836. var
  87837. //DDPF_ALPHAPIXELS = 0x1,
  87838. //DDPF_ALPHA = 0x2,
  87839. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87840. //DDPF_YUV = 0x200,
  87841. DDPF_LUMINANCE = 0x20000;
  87842. function FourCCToInt32(value) {
  87843. return value.charCodeAt(0) +
  87844. (value.charCodeAt(1) << 8) +
  87845. (value.charCodeAt(2) << 16) +
  87846. (value.charCodeAt(3) << 24);
  87847. }
  87848. function Int32ToFourCC(value) {
  87849. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87850. }
  87851. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87852. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87853. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87854. var FOURCC_DX10 = FourCCToInt32("DX10");
  87855. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87856. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87857. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87858. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87859. var headerLengthInt = 31; // The header length in 32 bit ints
  87860. // Offsets into the header array
  87861. var off_magic = 0;
  87862. var off_size = 1;
  87863. var off_flags = 2;
  87864. var off_height = 3;
  87865. var off_width = 4;
  87866. var off_mipmapCount = 7;
  87867. var off_pfFlags = 20;
  87868. var off_pfFourCC = 21;
  87869. var off_RGBbpp = 22;
  87870. var off_RMask = 23;
  87871. var off_GMask = 24;
  87872. var off_BMask = 25;
  87873. var off_AMask = 26;
  87874. // var off_caps1 = 27;
  87875. var off_caps2 = 28;
  87876. // var off_caps3 = 29;
  87877. // var off_caps4 = 30;
  87878. var off_dxgiFormat = 32;
  87879. ;
  87880. var DDSTools = /** @class */ (function () {
  87881. function DDSTools() {
  87882. }
  87883. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87884. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87885. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87886. var mipmapCount = 1;
  87887. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87888. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87889. }
  87890. var fourCC = header[off_pfFourCC];
  87891. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87892. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87893. switch (fourCC) {
  87894. case FOURCC_D3DFMT_R16G16B16A16F:
  87895. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87896. break;
  87897. case FOURCC_D3DFMT_R32G32B32A32F:
  87898. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87899. break;
  87900. case FOURCC_DX10:
  87901. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87902. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87903. break;
  87904. }
  87905. }
  87906. return {
  87907. width: header[off_width],
  87908. height: header[off_height],
  87909. mipmapCount: mipmapCount,
  87910. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87911. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87912. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87913. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87914. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87915. dxgiFormat: dxgiFormat,
  87916. textureType: textureType
  87917. };
  87918. };
  87919. DDSTools._ToHalfFloat = function (value) {
  87920. if (!DDSTools._FloatView) {
  87921. DDSTools._FloatView = new Float32Array(1);
  87922. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87923. }
  87924. DDSTools._FloatView[0] = value;
  87925. var x = DDSTools._Int32View[0];
  87926. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87927. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87928. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87929. /* If zero, or denormal, or exponent underflows too much for a denormal
  87930. * half, return signed zero. */
  87931. if (e < 103) {
  87932. return bits;
  87933. }
  87934. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87935. if (e > 142) {
  87936. bits |= 0x7c00;
  87937. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87938. * not Inf, so make sure we set one mantissa bit too. */
  87939. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87940. return bits;
  87941. }
  87942. /* If exponent underflows but not too much, return a denormal */
  87943. if (e < 113) {
  87944. m |= 0x0800;
  87945. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87946. * to 1, which is OK. */
  87947. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87948. return bits;
  87949. }
  87950. bits |= ((e - 112) << 10) | (m >> 1);
  87951. bits += m & 1;
  87952. return bits;
  87953. };
  87954. DDSTools._FromHalfFloat = function (value) {
  87955. var s = (value & 0x8000) >> 15;
  87956. var e = (value & 0x7C00) >> 10;
  87957. var f = value & 0x03FF;
  87958. if (e === 0) {
  87959. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87960. }
  87961. else if (e == 0x1F) {
  87962. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87963. }
  87964. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87965. };
  87966. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87967. var destArray = new Float32Array(dataLength);
  87968. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87969. var index = 0;
  87970. for (var y = 0; y < height; y++) {
  87971. for (var x = 0; x < width; x++) {
  87972. var srcPos = (x + y * width) * 4;
  87973. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87974. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87975. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87976. if (DDSTools.StoreLODInAlphaChannel) {
  87977. destArray[index + 3] = lod;
  87978. }
  87979. else {
  87980. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87981. }
  87982. index += 4;
  87983. }
  87984. }
  87985. return destArray;
  87986. };
  87987. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87988. if (DDSTools.StoreLODInAlphaChannel) {
  87989. var destArray = new Uint16Array(dataLength);
  87990. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87991. var index = 0;
  87992. for (var y = 0; y < height; y++) {
  87993. for (var x = 0; x < width; x++) {
  87994. var srcPos = (x + y * width) * 4;
  87995. destArray[index] = srcData[srcPos];
  87996. destArray[index + 1] = srcData[srcPos + 1];
  87997. destArray[index + 2] = srcData[srcPos + 2];
  87998. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87999. index += 4;
  88000. }
  88001. }
  88002. return destArray;
  88003. }
  88004. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  88005. };
  88006. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88007. if (DDSTools.StoreLODInAlphaChannel) {
  88008. var destArray = new Float32Array(dataLength);
  88009. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88010. var index = 0;
  88011. for (var y = 0; y < height; y++) {
  88012. for (var x = 0; x < width; x++) {
  88013. var srcPos = (x + y * width) * 4;
  88014. destArray[index] = srcData[srcPos];
  88015. destArray[index + 1] = srcData[srcPos + 1];
  88016. destArray[index + 2] = srcData[srcPos + 2];
  88017. destArray[index + 3] = lod;
  88018. index += 4;
  88019. }
  88020. }
  88021. return destArray;
  88022. }
  88023. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  88024. };
  88025. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88026. var destArray = new Uint8Array(dataLength);
  88027. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88028. var index = 0;
  88029. for (var y = 0; y < height; y++) {
  88030. for (var x = 0; x < width; x++) {
  88031. var srcPos = (x + y * width) * 4;
  88032. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  88033. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  88034. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  88035. if (DDSTools.StoreLODInAlphaChannel) {
  88036. destArray[index + 3] = lod;
  88037. }
  88038. else {
  88039. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  88040. }
  88041. index += 4;
  88042. }
  88043. }
  88044. return destArray;
  88045. };
  88046. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88047. var destArray = new Uint8Array(dataLength);
  88048. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88049. var index = 0;
  88050. for (var y = 0; y < height; y++) {
  88051. for (var x = 0; x < width; x++) {
  88052. var srcPos = (x + y * width) * 4;
  88053. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  88054. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  88055. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  88056. if (DDSTools.StoreLODInAlphaChannel) {
  88057. destArray[index + 3] = lod;
  88058. }
  88059. else {
  88060. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  88061. }
  88062. index += 4;
  88063. }
  88064. }
  88065. return destArray;
  88066. };
  88067. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  88068. var byteArray = new Uint8Array(dataLength);
  88069. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88070. var index = 0;
  88071. for (var y = 0; y < height; y++) {
  88072. for (var x = 0; x < width; x++) {
  88073. var srcPos = (x + y * width) * 4;
  88074. byteArray[index] = srcData[srcPos + rOffset];
  88075. byteArray[index + 1] = srcData[srcPos + gOffset];
  88076. byteArray[index + 2] = srcData[srcPos + bOffset];
  88077. byteArray[index + 3] = srcData[srcPos + aOffset];
  88078. index += 4;
  88079. }
  88080. }
  88081. return byteArray;
  88082. };
  88083. DDSTools._ExtractLongWordOrder = function (value) {
  88084. if (value === 0 || value === 255 || value === -16777216) {
  88085. return 0;
  88086. }
  88087. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  88088. };
  88089. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  88090. var byteArray = new Uint8Array(dataLength);
  88091. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88092. var index = 0;
  88093. for (var y = 0; y < height; y++) {
  88094. for (var x = 0; x < width; x++) {
  88095. var srcPos = (x + y * width) * 3;
  88096. byteArray[index] = srcData[srcPos + rOffset];
  88097. byteArray[index + 1] = srcData[srcPos + gOffset];
  88098. byteArray[index + 2] = srcData[srcPos + bOffset];
  88099. index += 3;
  88100. }
  88101. }
  88102. return byteArray;
  88103. };
  88104. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  88105. var byteArray = new Uint8Array(dataLength);
  88106. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88107. var index = 0;
  88108. for (var y = 0; y < height; y++) {
  88109. for (var x = 0; x < width; x++) {
  88110. var srcPos = (x + y * width);
  88111. byteArray[index] = srcData[srcPos];
  88112. index++;
  88113. }
  88114. }
  88115. return byteArray;
  88116. };
  88117. /**
  88118. * Uploads DDS Levels to a Babylon Texture
  88119. * @hidden
  88120. */
  88121. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  88122. if (lodIndex === void 0) { lodIndex = -1; }
  88123. var sphericalPolynomialFaces = null;
  88124. if (info.sphericalPolynomial) {
  88125. sphericalPolynomialFaces = new Array();
  88126. }
  88127. var ext = engine.getCaps().s3tc;
  88128. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88129. var fourCC, width, height, dataLength = 0, dataOffset;
  88130. var byteArray, mipmapCount, mip;
  88131. var internalCompressedFormat = 0;
  88132. var blockBytes = 1;
  88133. if (header[off_magic] !== DDS_MAGIC) {
  88134. BABYLON.Tools.Error("Invalid magic number in DDS header");
  88135. return;
  88136. }
  88137. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  88138. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  88139. return;
  88140. }
  88141. if (info.isCompressed && !ext) {
  88142. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  88143. return;
  88144. }
  88145. var bpp = header[off_RGBbpp];
  88146. dataOffset = header[off_size] + 4;
  88147. var computeFormats = false;
  88148. if (info.isFourCC) {
  88149. fourCC = header[off_pfFourCC];
  88150. switch (fourCC) {
  88151. case FOURCC_DXT1:
  88152. blockBytes = 8;
  88153. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  88154. break;
  88155. case FOURCC_DXT3:
  88156. blockBytes = 16;
  88157. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  88158. break;
  88159. case FOURCC_DXT5:
  88160. blockBytes = 16;
  88161. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  88162. break;
  88163. case FOURCC_D3DFMT_R16G16B16A16F:
  88164. computeFormats = true;
  88165. break;
  88166. case FOURCC_D3DFMT_R32G32B32A32F:
  88167. computeFormats = true;
  88168. break;
  88169. case FOURCC_DX10:
  88170. // There is an additionnal header so dataOffset need to be changed
  88171. dataOffset += 5 * 4; // 5 uints
  88172. var supported = false;
  88173. switch (info.dxgiFormat) {
  88174. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  88175. computeFormats = true;
  88176. supported = true;
  88177. break;
  88178. case DXGI_FORMAT_B8G8R8X8_UNORM:
  88179. info.isRGB = true;
  88180. info.isFourCC = false;
  88181. bpp = 32;
  88182. supported = true;
  88183. break;
  88184. }
  88185. if (supported) {
  88186. break;
  88187. }
  88188. default:
  88189. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  88190. return;
  88191. }
  88192. }
  88193. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  88194. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  88195. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  88196. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  88197. if (computeFormats) {
  88198. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  88199. }
  88200. mipmapCount = 1;
  88201. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  88202. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88203. }
  88204. for (var face = 0; face < faces; face++) {
  88205. width = header[off_width];
  88206. height = header[off_height];
  88207. for (mip = 0; mip < mipmapCount; ++mip) {
  88208. if (lodIndex === -1 || lodIndex === mip) {
  88209. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  88210. var i = (lodIndex === -1) ? mip : 0;
  88211. if (!info.isCompressed && info.isFourCC) {
  88212. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88213. dataLength = width * height * 4;
  88214. var floatArray = null;
  88215. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  88216. if (bpp === 128) {
  88217. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88218. if (sphericalPolynomialFaces && i == 0) {
  88219. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88220. }
  88221. }
  88222. else if (bpp === 64) {
  88223. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88224. if (sphericalPolynomialFaces && i == 0) {
  88225. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88226. }
  88227. }
  88228. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88229. }
  88230. else {
  88231. if (bpp === 128) {
  88232. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88233. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88234. if (sphericalPolynomialFaces && i == 0) {
  88235. sphericalPolynomialFaces.push(floatArray);
  88236. }
  88237. }
  88238. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  88239. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88240. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88241. if (sphericalPolynomialFaces && i == 0) {
  88242. sphericalPolynomialFaces.push(floatArray);
  88243. }
  88244. }
  88245. else { // 64
  88246. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88247. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88248. if (sphericalPolynomialFaces && i == 0) {
  88249. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88250. }
  88251. }
  88252. }
  88253. if (floatArray) {
  88254. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  88255. }
  88256. }
  88257. else if (info.isRGB) {
  88258. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88259. if (bpp === 24) {
  88260. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  88261. dataLength = width * height * 3;
  88262. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  88263. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88264. }
  88265. else { // 32
  88266. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88267. dataLength = width * height * 4;
  88268. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  88269. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88270. }
  88271. }
  88272. else if (info.isLuminance) {
  88273. var unpackAlignment = engine._getUnpackAlignement();
  88274. var unpaddedRowSize = width;
  88275. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  88276. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  88277. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  88278. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  88279. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88280. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88281. }
  88282. else {
  88283. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  88284. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  88285. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88286. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  88287. }
  88288. }
  88289. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  88290. width *= 0.5;
  88291. height *= 0.5;
  88292. width = Math.max(1.0, width);
  88293. height = Math.max(1.0, height);
  88294. }
  88295. if (currentFace !== undefined) {
  88296. // Loading a single face
  88297. break;
  88298. }
  88299. }
  88300. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  88301. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  88302. size: header[off_width],
  88303. right: sphericalPolynomialFaces[0],
  88304. left: sphericalPolynomialFaces[1],
  88305. up: sphericalPolynomialFaces[2],
  88306. down: sphericalPolynomialFaces[3],
  88307. front: sphericalPolynomialFaces[4],
  88308. back: sphericalPolynomialFaces[5],
  88309. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  88310. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88311. gammaSpace: false,
  88312. });
  88313. }
  88314. else {
  88315. info.sphericalPolynomial = undefined;
  88316. }
  88317. };
  88318. DDSTools.StoreLODInAlphaChannel = false;
  88319. return DDSTools;
  88320. }());
  88321. BABYLON.DDSTools = DDSTools;
  88322. })(BABYLON || (BABYLON = {}));
  88323. //# sourceMappingURL=babylon.dds.js.map
  88324. var BABYLON;
  88325. (function (BABYLON) {
  88326. /**
  88327. * Implementation of the DDS Texture Loader.
  88328. */
  88329. var DDSTextureLoader = /** @class */ (function () {
  88330. function DDSTextureLoader() {
  88331. /**
  88332. * Defines wether the loader supports cascade loading the different faces.
  88333. */
  88334. this.supportCascades = true;
  88335. }
  88336. /**
  88337. * This returns if the loader support the current file information.
  88338. * @param extension defines the file extension of the file being loaded
  88339. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88340. * @param fallback defines the fallback internal texture if any
  88341. * @param isBase64 defines whether the texture is encoded as a base64
  88342. * @param isBuffer defines whether the texture data are stored as a buffer
  88343. * @returns true if the loader can load the specified file
  88344. */
  88345. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88346. return extension.indexOf(".dds") === 0;
  88347. };
  88348. /**
  88349. * Transform the url before loading if required.
  88350. * @param rootUrl the url of the texture
  88351. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88352. * @returns the transformed texture
  88353. */
  88354. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88355. return rootUrl;
  88356. };
  88357. /**
  88358. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88359. * @param rootUrl the url of the texture
  88360. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88361. * @returns the fallback texture
  88362. */
  88363. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88364. return null;
  88365. };
  88366. /**
  88367. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88368. * @param data contains the texture data
  88369. * @param texture defines the BabylonJS internal texture
  88370. * @param createPolynomials will be true if polynomials have been requested
  88371. * @param onLoad defines the callback to trigger once the texture is ready
  88372. * @param onError defines the callback to trigger in case of error
  88373. */
  88374. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  88375. var engine = texture.getEngine();
  88376. var info;
  88377. var loadMipmap = false;
  88378. if (Array.isArray(imgs)) {
  88379. for (var index = 0; index < imgs.length; index++) {
  88380. var data_1 = imgs[index];
  88381. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  88382. texture.width = info.width;
  88383. texture.height = info.height;
  88384. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  88385. engine._unpackFlipY(info.isCompressed);
  88386. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  88387. if (!info.isFourCC && info.mipmapCount === 1) {
  88388. engine.generateMipMapsForCubemap(texture);
  88389. }
  88390. }
  88391. }
  88392. else {
  88393. var data = imgs;
  88394. info = BABYLON.DDSTools.GetDDSInfo(data);
  88395. texture.width = info.width;
  88396. texture.height = info.height;
  88397. if (createPolynomials) {
  88398. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  88399. }
  88400. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  88401. engine._unpackFlipY(info.isCompressed);
  88402. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  88403. if (!info.isFourCC && info.mipmapCount === 1) {
  88404. engine.generateMipMapsForCubemap(texture);
  88405. }
  88406. }
  88407. engine._setCubeMapTextureParams(loadMipmap);
  88408. texture.isReady = true;
  88409. if (onLoad) {
  88410. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  88411. }
  88412. };
  88413. /**
  88414. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88415. * @param data contains the texture data
  88416. * @param texture defines the BabylonJS internal texture
  88417. * @param callback defines the method to call once ready to upload
  88418. */
  88419. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  88420. var info = BABYLON.DDSTools.GetDDSInfo(data);
  88421. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  88422. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  88423. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  88424. });
  88425. };
  88426. return DDSTextureLoader;
  88427. }());
  88428. // Register the loader.
  88429. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  88430. })(BABYLON || (BABYLON = {}));
  88431. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  88432. var BABYLON;
  88433. (function (BABYLON) {
  88434. /*
  88435. * Based on jsTGALoader - Javascript loader for TGA file
  88436. * By Vincent Thibault
  88437. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  88438. */
  88439. var TGATools = /** @class */ (function () {
  88440. function TGATools() {
  88441. }
  88442. TGATools.GetTGAHeader = function (data) {
  88443. var offset = 0;
  88444. var header = {
  88445. id_length: data[offset++],
  88446. colormap_type: data[offset++],
  88447. image_type: data[offset++],
  88448. colormap_index: data[offset++] | data[offset++] << 8,
  88449. colormap_length: data[offset++] | data[offset++] << 8,
  88450. colormap_size: data[offset++],
  88451. origin: [
  88452. data[offset++] | data[offset++] << 8,
  88453. data[offset++] | data[offset++] << 8
  88454. ],
  88455. width: data[offset++] | data[offset++] << 8,
  88456. height: data[offset++] | data[offset++] << 8,
  88457. pixel_size: data[offset++],
  88458. flags: data[offset++]
  88459. };
  88460. return header;
  88461. };
  88462. /**
  88463. * Uploads TGA content to a Babylon Texture
  88464. * @hidden
  88465. */
  88466. TGATools.UploadContent = function (texture, data) {
  88467. // Not enough data to contain header ?
  88468. if (data.length < 19) {
  88469. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  88470. return;
  88471. }
  88472. // Read Header
  88473. var offset = 18;
  88474. var header = TGATools.GetTGAHeader(data);
  88475. // Assume it's a valid Targa file.
  88476. if (header.id_length + offset > data.length) {
  88477. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  88478. return;
  88479. }
  88480. // Skip not needed data
  88481. offset += header.id_length;
  88482. var use_rle = false;
  88483. var use_pal = false;
  88484. var use_grey = false;
  88485. // Get some informations.
  88486. switch (header.image_type) {
  88487. case TGATools._TYPE_RLE_INDEXED:
  88488. use_rle = true;
  88489. case TGATools._TYPE_INDEXED:
  88490. use_pal = true;
  88491. break;
  88492. case TGATools._TYPE_RLE_RGB:
  88493. use_rle = true;
  88494. case TGATools._TYPE_RGB:
  88495. // use_rgb = true;
  88496. break;
  88497. case TGATools._TYPE_RLE_GREY:
  88498. use_rle = true;
  88499. case TGATools._TYPE_GREY:
  88500. use_grey = true;
  88501. break;
  88502. }
  88503. var pixel_data;
  88504. // var numAlphaBits = header.flags & 0xf;
  88505. var pixel_size = header.pixel_size >> 3;
  88506. var pixel_total = header.width * header.height * pixel_size;
  88507. // Read palettes
  88508. var palettes;
  88509. if (use_pal) {
  88510. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  88511. }
  88512. // Read LRE
  88513. if (use_rle) {
  88514. pixel_data = new Uint8Array(pixel_total);
  88515. var c, count, i;
  88516. var localOffset = 0;
  88517. var pixels = new Uint8Array(pixel_size);
  88518. while (offset < pixel_total && localOffset < pixel_total) {
  88519. c = data[offset++];
  88520. count = (c & 0x7f) + 1;
  88521. // RLE pixels
  88522. if (c & 0x80) {
  88523. // Bind pixel tmp array
  88524. for (i = 0; i < pixel_size; ++i) {
  88525. pixels[i] = data[offset++];
  88526. }
  88527. // Copy pixel array
  88528. for (i = 0; i < count; ++i) {
  88529. pixel_data.set(pixels, localOffset + i * pixel_size);
  88530. }
  88531. localOffset += pixel_size * count;
  88532. }
  88533. // Raw pixels
  88534. else {
  88535. count *= pixel_size;
  88536. for (i = 0; i < count; ++i) {
  88537. pixel_data[localOffset + i] = data[offset++];
  88538. }
  88539. localOffset += count;
  88540. }
  88541. }
  88542. }
  88543. // RAW Pixels
  88544. else {
  88545. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  88546. }
  88547. // Load to texture
  88548. var x_start, y_start, x_step, y_step, y_end, x_end;
  88549. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  88550. default:
  88551. case TGATools._ORIGIN_UL:
  88552. x_start = 0;
  88553. x_step = 1;
  88554. x_end = header.width;
  88555. y_start = 0;
  88556. y_step = 1;
  88557. y_end = header.height;
  88558. break;
  88559. case TGATools._ORIGIN_BL:
  88560. x_start = 0;
  88561. x_step = 1;
  88562. x_end = header.width;
  88563. y_start = header.height - 1;
  88564. y_step = -1;
  88565. y_end = -1;
  88566. break;
  88567. case TGATools._ORIGIN_UR:
  88568. x_start = header.width - 1;
  88569. x_step = -1;
  88570. x_end = -1;
  88571. y_start = 0;
  88572. y_step = 1;
  88573. y_end = header.height;
  88574. break;
  88575. case TGATools._ORIGIN_BR:
  88576. x_start = header.width - 1;
  88577. x_step = -1;
  88578. x_end = -1;
  88579. y_start = header.height - 1;
  88580. y_step = -1;
  88581. y_end = -1;
  88582. break;
  88583. }
  88584. // Load the specify method
  88585. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  88586. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  88587. var engine = texture.getEngine();
  88588. engine._uploadDataToTextureDirectly(texture, imageData);
  88589. };
  88590. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88591. var image = pixel_data, colormap = palettes;
  88592. var width = header.width, height = header.height;
  88593. var color, i = 0, x, y;
  88594. var imageData = new Uint8Array(width * height * 4);
  88595. for (y = y_start; y !== y_end; y += y_step) {
  88596. for (x = x_start; x !== x_end; x += x_step, i++) {
  88597. color = image[i];
  88598. imageData[(x + width * y) * 4 + 3] = 255;
  88599. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  88600. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  88601. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  88602. }
  88603. }
  88604. return imageData;
  88605. };
  88606. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88607. var image = pixel_data;
  88608. var width = header.width, height = header.height;
  88609. var color, i = 0, x, y;
  88610. var imageData = new Uint8Array(width * height * 4);
  88611. for (y = y_start; y !== y_end; y += y_step) {
  88612. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88613. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  88614. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  88615. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  88616. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  88617. imageData[(x + width * y) * 4 + 0] = r;
  88618. imageData[(x + width * y) * 4 + 1] = g;
  88619. imageData[(x + width * y) * 4 + 2] = b;
  88620. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  88621. }
  88622. }
  88623. return imageData;
  88624. };
  88625. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88626. var image = pixel_data;
  88627. var width = header.width, height = header.height;
  88628. var i = 0, x, y;
  88629. var imageData = new Uint8Array(width * height * 4);
  88630. for (y = y_start; y !== y_end; y += y_step) {
  88631. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  88632. imageData[(x + width * y) * 4 + 3] = 255;
  88633. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88634. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88635. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88636. }
  88637. }
  88638. return imageData;
  88639. };
  88640. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88641. var image = pixel_data;
  88642. var width = header.width, height = header.height;
  88643. var i = 0, x, y;
  88644. var imageData = new Uint8Array(width * height * 4);
  88645. for (y = y_start; y !== y_end; y += y_step) {
  88646. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  88647. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88648. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88649. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88650. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  88651. }
  88652. }
  88653. return imageData;
  88654. };
  88655. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88656. var image = pixel_data;
  88657. var width = header.width, height = header.height;
  88658. var color, i = 0, x, y;
  88659. var imageData = new Uint8Array(width * height * 4);
  88660. for (y = y_start; y !== y_end; y += y_step) {
  88661. for (x = x_start; x !== x_end; x += x_step, i++) {
  88662. color = image[i];
  88663. imageData[(x + width * y) * 4 + 0] = color;
  88664. imageData[(x + width * y) * 4 + 1] = color;
  88665. imageData[(x + width * y) * 4 + 2] = color;
  88666. imageData[(x + width * y) * 4 + 3] = 255;
  88667. }
  88668. }
  88669. return imageData;
  88670. };
  88671. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88672. var image = pixel_data;
  88673. var width = header.width, height = header.height;
  88674. var i = 0, x, y;
  88675. var imageData = new Uint8Array(width * height * 4);
  88676. for (y = y_start; y !== y_end; y += y_step) {
  88677. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88678. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  88679. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  88680. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88681. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  88682. }
  88683. }
  88684. return imageData;
  88685. };
  88686. //private static _TYPE_NO_DATA = 0;
  88687. TGATools._TYPE_INDEXED = 1;
  88688. TGATools._TYPE_RGB = 2;
  88689. TGATools._TYPE_GREY = 3;
  88690. TGATools._TYPE_RLE_INDEXED = 9;
  88691. TGATools._TYPE_RLE_RGB = 10;
  88692. TGATools._TYPE_RLE_GREY = 11;
  88693. TGATools._ORIGIN_MASK = 0x30;
  88694. TGATools._ORIGIN_SHIFT = 0x04;
  88695. TGATools._ORIGIN_BL = 0x00;
  88696. TGATools._ORIGIN_BR = 0x01;
  88697. TGATools._ORIGIN_UL = 0x02;
  88698. TGATools._ORIGIN_UR = 0x03;
  88699. return TGATools;
  88700. }());
  88701. BABYLON.TGATools = TGATools;
  88702. })(BABYLON || (BABYLON = {}));
  88703. //# sourceMappingURL=babylon.tga.js.map
  88704. var BABYLON;
  88705. (function (BABYLON) {
  88706. /**
  88707. * Implementation of the TGA Texture Loader.
  88708. */
  88709. var TGATextureLoader = /** @class */ (function () {
  88710. function TGATextureLoader() {
  88711. /**
  88712. * Defines wether the loader supports cascade loading the different faces.
  88713. */
  88714. this.supportCascades = false;
  88715. }
  88716. /**
  88717. * This returns if the loader support the current file information.
  88718. * @param extension defines the file extension of the file being loaded
  88719. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88720. * @param fallback defines the fallback internal texture if any
  88721. * @param isBase64 defines whether the texture is encoded as a base64
  88722. * @param isBuffer defines whether the texture data are stored as a buffer
  88723. * @returns true if the loader can load the specified file
  88724. */
  88725. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88726. return extension.indexOf(".tga") === 0;
  88727. };
  88728. /**
  88729. * Transform the url before loading if required.
  88730. * @param rootUrl the url of the texture
  88731. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88732. * @returns the transformed texture
  88733. */
  88734. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88735. return rootUrl;
  88736. };
  88737. /**
  88738. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88739. * @param rootUrl the url of the texture
  88740. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88741. * @returns the fallback texture
  88742. */
  88743. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88744. return null;
  88745. };
  88746. /**
  88747. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88748. * @param data contains the texture data
  88749. * @param texture defines the BabylonJS internal texture
  88750. * @param createPolynomials will be true if polynomials have been requested
  88751. * @param onLoad defines the callback to trigger once the texture is ready
  88752. * @param onError defines the callback to trigger in case of error
  88753. */
  88754. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88755. throw ".env not supported in Cube.";
  88756. };
  88757. /**
  88758. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88759. * @param data contains the texture data
  88760. * @param texture defines the BabylonJS internal texture
  88761. * @param callback defines the method to call once ready to upload
  88762. */
  88763. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  88764. var uintData = new Uint8Array(data);
  88765. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  88766. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  88767. BABYLON.TGATools.UploadContent(texture, uintData);
  88768. });
  88769. };
  88770. return TGATextureLoader;
  88771. }());
  88772. // Register the loader.
  88773. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  88774. })(BABYLON || (BABYLON = {}));
  88775. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  88776. var BABYLON;
  88777. (function (BABYLON) {
  88778. /**
  88779. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88780. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88781. */
  88782. var KhronosTextureContainer = /** @class */ (function () {
  88783. /**
  88784. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88785. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88786. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88787. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88788. */
  88789. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88790. this.arrayBuffer = arrayBuffer;
  88791. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88792. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88793. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88794. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88795. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88796. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88797. BABYLON.Tools.Error("texture missing KTX identifier");
  88798. return;
  88799. }
  88800. // load the reset of the header in native 32 bit int
  88801. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88802. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88803. var oppositeEndianess = header[0] === 0x01020304;
  88804. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88805. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88806. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88807. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88808. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88809. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88810. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88811. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88812. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88813. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88814. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88815. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88816. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88817. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88818. if (this.glType !== 0) {
  88819. BABYLON.Tools.Error("only compressed formats currently supported");
  88820. return;
  88821. }
  88822. else {
  88823. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88824. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88825. }
  88826. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88827. BABYLON.Tools.Error("only 2D textures currently supported");
  88828. return;
  88829. }
  88830. if (this.numberOfArrayElements !== 0) {
  88831. BABYLON.Tools.Error("texture arrays not currently supported");
  88832. return;
  88833. }
  88834. if (this.numberOfFaces !== facesExpected) {
  88835. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88836. return;
  88837. }
  88838. // we now have a completely validated file, so could use existence of loadType as success
  88839. // would need to make this more elaborate & adjust checks above to support more than one load type
  88840. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88841. }
  88842. // not as fast hardware based, but will probably never need to use
  88843. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88844. return ((val & 0xFF) << 24)
  88845. | ((val & 0xFF00) << 8)
  88846. | ((val >> 8) & 0xFF00)
  88847. | ((val >> 24) & 0xFF);
  88848. };
  88849. /**
  88850. * Uploads KTX content to a Babylon Texture.
  88851. * It is assumed that the texture has already been created & is currently bound
  88852. * @hidden
  88853. */
  88854. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88855. switch (this.loadType) {
  88856. case KhronosTextureContainer.COMPRESSED_2D:
  88857. this._upload2DCompressedLevels(texture, loadMipmaps);
  88858. break;
  88859. case KhronosTextureContainer.TEX_2D:
  88860. case KhronosTextureContainer.COMPRESSED_3D:
  88861. case KhronosTextureContainer.TEX_3D:
  88862. }
  88863. };
  88864. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88865. // initialize width & height for level 1
  88866. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88867. var width = this.pixelWidth;
  88868. var height = this.pixelHeight;
  88869. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88870. for (var level = 0; level < mipmapCount; level++) {
  88871. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88872. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88873. for (var face = 0; face < this.numberOfFaces; face++) {
  88874. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88875. var engine = texture.getEngine();
  88876. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88877. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88878. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88879. }
  88880. width = Math.max(1.0, width * 0.5);
  88881. height = Math.max(1.0, height * 0.5);
  88882. }
  88883. };
  88884. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88885. // load types
  88886. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88887. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88888. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88889. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88890. return KhronosTextureContainer;
  88891. }());
  88892. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88893. })(BABYLON || (BABYLON = {}));
  88894. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88895. var BABYLON;
  88896. (function (BABYLON) {
  88897. /**
  88898. * Implementation of the KTX Texture Loader.
  88899. */
  88900. var KTXTextureLoader = /** @class */ (function () {
  88901. function KTXTextureLoader() {
  88902. /**
  88903. * Defines wether the loader supports cascade loading the different faces.
  88904. */
  88905. this.supportCascades = false;
  88906. }
  88907. /**
  88908. * This returns if the loader support the current file information.
  88909. * @param extension defines the file extension of the file being loaded
  88910. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88911. * @param fallback defines the fallback internal texture if any
  88912. * @param isBase64 defines whether the texture is encoded as a base64
  88913. * @param isBuffer defines whether the texture data are stored as a buffer
  88914. * @returns true if the loader can load the specified file
  88915. */
  88916. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88917. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  88918. return true;
  88919. }
  88920. return false;
  88921. };
  88922. /**
  88923. * Transform the url before loading if required.
  88924. * @param rootUrl the url of the texture
  88925. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88926. * @returns the transformed texture
  88927. */
  88928. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88929. var lastDot = rootUrl.lastIndexOf('.');
  88930. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  88931. };
  88932. /**
  88933. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88934. * @param rootUrl the url of the texture
  88935. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88936. * @returns the fallback texture
  88937. */
  88938. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88939. // remove the format appended to the rootUrl in the original createCubeTexture call.
  88940. var exp = new RegExp("" + textureFormatInUse + "$");
  88941. return rootUrl.replace(exp, "");
  88942. };
  88943. /**
  88944. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88945. * @param data contains the texture data
  88946. * @param texture defines the BabylonJS internal texture
  88947. * @param createPolynomials will be true if polynomials have been requested
  88948. * @param onLoad defines the callback to trigger once the texture is ready
  88949. * @param onError defines the callback to trigger in case of error
  88950. */
  88951. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88952. if (Array.isArray(data)) {
  88953. return;
  88954. }
  88955. var engine = texture.getEngine();
  88956. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  88957. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  88958. engine._unpackFlipY(true);
  88959. ktx.uploadLevels(texture, texture.generateMipMaps);
  88960. texture.width = ktx.pixelWidth;
  88961. texture.height = ktx.pixelHeight;
  88962. engine._setCubeMapTextureParams(loadMipmap);
  88963. texture.isReady = true;
  88964. };
  88965. /**
  88966. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88967. * @param data contains the texture data
  88968. * @param texture defines the BabylonJS internal texture
  88969. * @param callback defines the method to call once ready to upload
  88970. */
  88971. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  88972. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  88973. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  88974. ktx.uploadLevels(texture, texture.generateMipMaps);
  88975. });
  88976. };
  88977. return KTXTextureLoader;
  88978. }());
  88979. // Register the loader.
  88980. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  88981. })(BABYLON || (BABYLON = {}));
  88982. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  88983. var BABYLON;
  88984. (function (BABYLON) {
  88985. /**
  88986. * Sets of helpers addressing the serialization and deserialization of environment texture
  88987. * stored in a BabylonJS env file.
  88988. * Those files are usually stored as .env files.
  88989. */
  88990. var EnvironmentTextureTools = /** @class */ (function () {
  88991. function EnvironmentTextureTools() {
  88992. }
  88993. /**
  88994. * Gets the environment info from an env file.
  88995. * @param data The array buffer containing the .env bytes.
  88996. * @returns the environment file info (the json header) if successfully parsed.
  88997. */
  88998. EnvironmentTextureTools.GetEnvInfo = function (data) {
  88999. var dataView = new DataView(data);
  89000. var pos = 0;
  89001. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89002. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  89003. BABYLON.Tools.Error('Not a babylon environment map');
  89004. return null;
  89005. }
  89006. }
  89007. // Read json manifest - collect characters up to null terminator
  89008. var manifestString = '';
  89009. var charCode = 0x00;
  89010. while ((charCode = dataView.getUint8(pos++))) {
  89011. manifestString += String.fromCharCode(charCode);
  89012. }
  89013. var manifest = JSON.parse(manifestString);
  89014. if (manifest.specular) {
  89015. // Extend the header with the position of the payload.
  89016. manifest.specular.specularDataPosition = pos;
  89017. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  89018. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  89019. }
  89020. return manifest;
  89021. };
  89022. /**
  89023. * Creates an environment texture from a loaded cube texture.
  89024. * @param texture defines the cube texture to convert in env file
  89025. * @return a promise containing the environment data if succesfull.
  89026. */
  89027. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  89028. var _this = this;
  89029. var internalTexture = texture.getInternalTexture();
  89030. if (!internalTexture) {
  89031. return Promise.reject("The cube texture is invalid.");
  89032. }
  89033. if (!texture._prefiltered) {
  89034. return Promise.reject("The cube texture is invalid (not prefiltered).");
  89035. }
  89036. var engine = internalTexture.getEngine();
  89037. if (engine && engine.premultipliedAlpha) {
  89038. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  89039. }
  89040. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  89041. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  89042. }
  89043. var canvas = engine.getRenderingCanvas();
  89044. if (!canvas) {
  89045. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  89046. }
  89047. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89048. if (!engine.getCaps().textureFloatRender) {
  89049. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89050. if (!engine.getCaps().textureHalfFloatRender) {
  89051. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  89052. }
  89053. }
  89054. var cubeWidth = internalTexture.width;
  89055. var hostingScene = new BABYLON.Scene(engine);
  89056. var specularTextures = {};
  89057. var promises = [];
  89058. // Read and collect all mipmaps data from the cube.
  89059. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  89060. mipmapsCount = Math.round(mipmapsCount);
  89061. var _loop_1 = function (i) {
  89062. var faceWidth = Math.pow(2, mipmapsCount - i);
  89063. var _loop_2 = function (face) {
  89064. var data = texture.readPixels(face, i);
  89065. // Creates a temp texture with the face data.
  89066. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  89067. // And rgbdEncode them.
  89068. var promise = new Promise(function (resolve, reject) {
  89069. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  89070. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  89071. rgbdPostProcess.onApply = function (effect) {
  89072. effect._bindTexture("textureSampler", tempTexture);
  89073. };
  89074. // As the process needs to happen on the main canvas, keep track of the current size
  89075. var currentW = engine.getRenderWidth();
  89076. var currentH = engine.getRenderHeight();
  89077. // Set the desired size for the texture
  89078. engine.setSize(faceWidth, faceWidth);
  89079. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  89080. // Reading datas from WebGL
  89081. BABYLON.Tools.ToBlob(canvas, function (blob) {
  89082. var fileReader = new FileReader();
  89083. fileReader.onload = function (event) {
  89084. var arrayBuffer = event.target.result;
  89085. specularTextures[i * 6 + face] = arrayBuffer;
  89086. resolve();
  89087. };
  89088. fileReader.readAsArrayBuffer(blob);
  89089. });
  89090. // Reapply the previous canvas size
  89091. engine.setSize(currentW, currentH);
  89092. });
  89093. });
  89094. promises.push(promise);
  89095. };
  89096. // All faces of the cube.
  89097. for (var face = 0; face < 6; face++) {
  89098. _loop_2(face);
  89099. }
  89100. };
  89101. for (var i = 0; i <= mipmapsCount; i++) {
  89102. _loop_1(i);
  89103. }
  89104. // Once all the textures haves been collected as RGBD stored in PNGs
  89105. return Promise.all(promises).then(function () {
  89106. // We can delete the hosting scene keeping track of all the creation objects
  89107. hostingScene.dispose();
  89108. // Creates the json header for the env texture
  89109. var info = {
  89110. version: 1,
  89111. width: cubeWidth,
  89112. irradiance: _this._CreateEnvTextureIrradiance(texture),
  89113. specular: {
  89114. mipmaps: [],
  89115. lodGenerationScale: texture.lodGenerationScale
  89116. }
  89117. };
  89118. // Sets the specular image data information
  89119. var position = 0;
  89120. for (var i = 0; i <= mipmapsCount; i++) {
  89121. for (var face = 0; face < 6; face++) {
  89122. var byteLength = specularTextures[i * 6 + face].byteLength;
  89123. info.specular.mipmaps.push({
  89124. length: byteLength,
  89125. position: position
  89126. });
  89127. position += byteLength;
  89128. }
  89129. }
  89130. // Encode the JSON as an array buffer
  89131. var infoString = JSON.stringify(info);
  89132. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  89133. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  89134. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  89135. infoView[i] = infoString.charCodeAt(i);
  89136. }
  89137. // Ends up with a null terminator for easier parsing
  89138. infoView[infoString.length] = 0x00;
  89139. // Computes the final required size and creates the storage
  89140. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  89141. var finalBuffer = new ArrayBuffer(totalSize);
  89142. var finalBufferView = new Uint8Array(finalBuffer);
  89143. var dataView = new DataView(finalBuffer);
  89144. // Copy the magic bytes identifying the file in
  89145. var pos = 0;
  89146. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89147. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  89148. }
  89149. // Add the json info
  89150. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  89151. pos += infoBuffer.byteLength;
  89152. // Finally inserts the texture data
  89153. for (var i = 0; i <= mipmapsCount; i++) {
  89154. for (var face = 0; face < 6; face++) {
  89155. var dataBuffer = specularTextures[i * 6 + face];
  89156. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  89157. pos += dataBuffer.byteLength;
  89158. }
  89159. }
  89160. // Voila
  89161. return finalBuffer;
  89162. });
  89163. };
  89164. /**
  89165. * Creates a JSON representation of the spherical data.
  89166. * @param texture defines the texture containing the polynomials
  89167. * @return the JSON representation of the spherical info
  89168. */
  89169. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  89170. var polynmials = texture.sphericalPolynomial;
  89171. if (polynmials == null) {
  89172. return null;
  89173. }
  89174. return {
  89175. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  89176. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  89177. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  89178. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  89179. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  89180. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  89181. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  89182. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  89183. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  89184. };
  89185. };
  89186. /**
  89187. * Uploads the texture info contained in the env file to the GPU.
  89188. * @param texture defines the internal texture to upload to
  89189. * @param arrayBuffer defines the buffer cotaining the data to load
  89190. * @param info defines the texture info retrieved through the GetEnvInfo method
  89191. * @returns a promise
  89192. */
  89193. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  89194. if (info.version !== 1) {
  89195. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  89196. }
  89197. var specularInfo = info.specular;
  89198. if (!specularInfo) {
  89199. // Nothing else parsed so far
  89200. return Promise.resolve();
  89201. }
  89202. // Double checks the enclosed info
  89203. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  89204. mipmapsCount = Math.round(mipmapsCount) + 1;
  89205. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  89206. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  89207. }
  89208. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  89209. var imageData = new Array(mipmapsCount);
  89210. for (var i = 0; i < mipmapsCount; i++) {
  89211. imageData[i] = new Array(6);
  89212. for (var face = 0; face < 6; face++) {
  89213. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  89214. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  89215. }
  89216. }
  89217. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  89218. };
  89219. /**
  89220. * Uploads the levels of image data to the GPU.
  89221. * @param texture defines the internal texture to upload to
  89222. * @param imageData defines the array buffer views of image data [mipmap][face]
  89223. * @returns a promise
  89224. */
  89225. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  89226. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  89227. throw new Error("Texture size must be a power of two");
  89228. }
  89229. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  89230. // Gets everything ready.
  89231. var engine = texture.getEngine();
  89232. var expandTexture = false;
  89233. var generateNonLODTextures = false;
  89234. var rgbdPostProcess = null;
  89235. var cubeRtt = null;
  89236. var lodTextures = null;
  89237. var caps = engine.getCaps();
  89238. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89239. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89240. texture.generateMipMaps = true;
  89241. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  89242. // Add extra process if texture lod is not supported
  89243. if (!caps.textureLOD) {
  89244. expandTexture = false;
  89245. generateNonLODTextures = true;
  89246. lodTextures = {};
  89247. }
  89248. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  89249. else if (engine.webGLVersion < 2) {
  89250. expandTexture = false;
  89251. }
  89252. // If half float available we can uncompress the texture
  89253. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  89254. expandTexture = true;
  89255. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89256. }
  89257. // If full float available we can uncompress the texture
  89258. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  89259. expandTexture = true;
  89260. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89261. }
  89262. // Expand the texture if possible
  89263. if (expandTexture) {
  89264. // Simply run through the decode PP
  89265. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  89266. texture._isRGBD = false;
  89267. texture.invertY = false;
  89268. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  89269. generateDepthBuffer: false,
  89270. generateMipMaps: true,
  89271. generateStencilBuffer: false,
  89272. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  89273. type: texture.type,
  89274. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  89275. });
  89276. }
  89277. else {
  89278. texture._isRGBD = true;
  89279. texture.invertY = true;
  89280. // In case of missing support, applies the same patch than DDS files.
  89281. if (generateNonLODTextures) {
  89282. var mipSlices = 3;
  89283. var scale = texture._lodGenerationScale;
  89284. var offset = texture._lodGenerationOffset;
  89285. for (var i = 0; i < mipSlices; i++) {
  89286. //compute LOD from even spacing in smoothness (matching shader calculation)
  89287. var smoothness = i / (mipSlices - 1);
  89288. var roughness = 1 - smoothness;
  89289. var minLODIndex = offset; // roughness = 0
  89290. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  89291. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  89292. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  89293. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  89294. glTextureFromLod.isCube = true;
  89295. glTextureFromLod.invertY = true;
  89296. glTextureFromLod.generateMipMaps = false;
  89297. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  89298. // Wrap in a base texture for easy binding.
  89299. var lodTexture = new BABYLON.BaseTexture(null);
  89300. lodTexture.isCube = true;
  89301. lodTexture._texture = glTextureFromLod;
  89302. lodTextures[mipmapIndex] = lodTexture;
  89303. switch (i) {
  89304. case 0:
  89305. texture._lodTextureLow = lodTexture;
  89306. break;
  89307. case 1:
  89308. texture._lodTextureMid = lodTexture;
  89309. break;
  89310. case 2:
  89311. texture._lodTextureHigh = lodTexture;
  89312. break;
  89313. }
  89314. }
  89315. }
  89316. }
  89317. var promises = [];
  89318. var _loop_3 = function (i) {
  89319. var _loop_4 = function (face) {
  89320. // Constructs an image element from image data
  89321. var bytes = imageData[i][face];
  89322. var blob = new Blob([bytes], { type: 'image/png' });
  89323. var url = URL.createObjectURL(blob);
  89324. var image = new Image();
  89325. image.src = url;
  89326. // Enqueue promise to upload to the texture.
  89327. var promise = new Promise(function (resolve, reject) {
  89328. image.onload = function () {
  89329. if (expandTexture) {
  89330. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  89331. reject(message);
  89332. }, image);
  89333. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  89334. // Uncompress the data to a RTT
  89335. rgbdPostProcess.onApply = function (effect) {
  89336. effect._bindTexture("textureSampler", tempTexture_1);
  89337. effect.setFloat2("scale", 1, 1);
  89338. };
  89339. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  89340. // Cleanup
  89341. engine.restoreDefaultFramebuffer();
  89342. tempTexture_1.dispose();
  89343. window.URL.revokeObjectURL(url);
  89344. resolve();
  89345. });
  89346. }
  89347. else {
  89348. engine._uploadImageToTexture(texture, image, face, i);
  89349. // Upload the face to the non lod texture support
  89350. if (generateNonLODTextures) {
  89351. var lodTexture = lodTextures[i];
  89352. if (lodTexture) {
  89353. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  89354. }
  89355. }
  89356. resolve();
  89357. }
  89358. };
  89359. image.onerror = function (error) {
  89360. reject(error);
  89361. };
  89362. });
  89363. promises.push(promise);
  89364. };
  89365. // All faces
  89366. for (var face = 0; face < 6; face++) {
  89367. _loop_4(face);
  89368. }
  89369. };
  89370. // All mipmaps up to provided number of images
  89371. for (var i = 0; i < imageData.length; i++) {
  89372. _loop_3(i);
  89373. }
  89374. // Fill remaining mipmaps with black textures.
  89375. if (imageData.length < mipmapsCount) {
  89376. var data = void 0;
  89377. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  89378. var dataLength = size * size * 4;
  89379. switch (texture.type) {
  89380. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  89381. data = new Uint8Array(dataLength);
  89382. break;
  89383. }
  89384. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  89385. data = new Uint16Array(dataLength);
  89386. break;
  89387. }
  89388. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  89389. data = new Float32Array(dataLength);
  89390. break;
  89391. }
  89392. }
  89393. for (var i = imageData.length; i < mipmapsCount; i++) {
  89394. for (var face = 0; face < 6; face++) {
  89395. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  89396. }
  89397. }
  89398. }
  89399. // Once all done, finishes the cleanup and return
  89400. return Promise.all(promises).then(function () {
  89401. // Release temp RTT.
  89402. if (cubeRtt) {
  89403. engine._releaseFramebufferObjects(cubeRtt);
  89404. cubeRtt._swapAndDie(texture);
  89405. }
  89406. // Release temp Post Process.
  89407. if (rgbdPostProcess) {
  89408. rgbdPostProcess.dispose();
  89409. }
  89410. // Flag internal texture as ready in case they are in use.
  89411. if (generateNonLODTextures) {
  89412. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  89413. texture._lodTextureHigh._texture.isReady = true;
  89414. }
  89415. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  89416. texture._lodTextureMid._texture.isReady = true;
  89417. }
  89418. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  89419. texture._lodTextureLow._texture.isReady = true;
  89420. }
  89421. }
  89422. });
  89423. };
  89424. /**
  89425. * Uploads spherical polynomials information to the texture.
  89426. * @param texture defines the texture we are trying to upload the information to
  89427. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  89428. */
  89429. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  89430. if (info.version !== 1) {
  89431. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  89432. }
  89433. var irradianceInfo = info.irradiance;
  89434. if (!irradianceInfo) {
  89435. return;
  89436. }
  89437. var sp = new BABYLON.SphericalPolynomial();
  89438. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  89439. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  89440. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  89441. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  89442. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  89443. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  89444. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  89445. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  89446. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  89447. texture._sphericalPolynomial = sp;
  89448. };
  89449. /**
  89450. * Magic number identifying the env file.
  89451. */
  89452. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  89453. return EnvironmentTextureTools;
  89454. }());
  89455. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  89456. })(BABYLON || (BABYLON = {}));
  89457. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  89458. var BABYLON;
  89459. (function (BABYLON) {
  89460. /**
  89461. * Implementation of the ENV Texture Loader.
  89462. */
  89463. var ENVTextureLoader = /** @class */ (function () {
  89464. function ENVTextureLoader() {
  89465. /**
  89466. * Defines wether the loader supports cascade loading the different faces.
  89467. */
  89468. this.supportCascades = false;
  89469. }
  89470. /**
  89471. * This returns if the loader support the current file information.
  89472. * @param extension defines the file extension of the file being loaded
  89473. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89474. * @param fallback defines the fallback internal texture if any
  89475. * @param isBase64 defines whether the texture is encoded as a base64
  89476. * @param isBuffer defines whether the texture data are stored as a buffer
  89477. * @returns true if the loader can load the specified file
  89478. */
  89479. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89480. return extension.indexOf(".env") === 0;
  89481. };
  89482. /**
  89483. * Transform the url before loading if required.
  89484. * @param rootUrl the url of the texture
  89485. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89486. * @returns the transformed texture
  89487. */
  89488. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89489. return rootUrl;
  89490. };
  89491. /**
  89492. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89493. * @param rootUrl the url of the texture
  89494. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89495. * @returns the fallback texture
  89496. */
  89497. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89498. return null;
  89499. };
  89500. /**
  89501. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89502. * @param data contains the texture data
  89503. * @param texture defines the BabylonJS internal texture
  89504. * @param createPolynomials will be true if polynomials have been requested
  89505. * @param onLoad defines the callback to trigger once the texture is ready
  89506. * @param onError defines the callback to trigger in case of error
  89507. */
  89508. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89509. if (Array.isArray(data)) {
  89510. return;
  89511. }
  89512. data = data;
  89513. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  89514. if (info) {
  89515. texture.width = info.width;
  89516. texture.height = info.width;
  89517. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  89518. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  89519. texture.isReady = true;
  89520. if (onLoad) {
  89521. onLoad();
  89522. }
  89523. });
  89524. }
  89525. else if (onError) {
  89526. onError("Can not parse the environment file", null);
  89527. }
  89528. };
  89529. /**
  89530. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89531. * @param data contains the texture data
  89532. * @param texture defines the BabylonJS internal texture
  89533. * @param callback defines the method to call once ready to upload
  89534. */
  89535. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  89536. throw ".env not supported in 2d.";
  89537. };
  89538. return ENVTextureLoader;
  89539. }());
  89540. // Register the loader.
  89541. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  89542. })(BABYLON || (BABYLON = {}));
  89543. //# sourceMappingURL=babylon.envTextureLoader.js.map
  89544. var BABYLON;
  89545. (function (BABYLON) {
  89546. /**
  89547. * Renders a layer on top of an existing scene
  89548. */
  89549. var UtilityLayerRenderer = /** @class */ (function () {
  89550. /**
  89551. * Instantiates a UtilityLayerRenderer
  89552. * @param originalScene the original scene that will be rendered on top of
  89553. */
  89554. function UtilityLayerRenderer(
  89555. /** the original scene that will be rendered on top of */
  89556. originalScene) {
  89557. var _this = this;
  89558. this.originalScene = originalScene;
  89559. this._pointerCaptures = {};
  89560. this._lastPointerEvents = {};
  89561. /**
  89562. * If the utility layer should automatically be rendered on top of existing scene
  89563. */
  89564. this.shouldRender = true;
  89565. /**
  89566. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  89567. */
  89568. this.onlyCheckPointerDownEvents = true;
  89569. /**
  89570. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  89571. */
  89572. this.processAllEvents = false;
  89573. /**
  89574. * Observable raised when the pointer move from the utility layer scene to the main scene
  89575. */
  89576. this.onPointerOutObservable = new BABYLON.Observable();
  89577. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  89578. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  89579. this.utilityLayerScene._allowPostProcessClear = false;
  89580. originalScene.getEngine().scenes.pop();
  89581. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  89582. this.utilityLayerScene.detachControl();
  89583. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  89584. if (!_this.processAllEvents) {
  89585. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  89586. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  89587. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  89588. return;
  89589. }
  89590. }
  89591. var pointerEvent = (prePointerInfo.event);
  89592. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  89593. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89594. return;
  89595. }
  89596. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  89597. if (!prePointerInfo.ray && utilityScenePick) {
  89598. prePointerInfo.ray = utilityScenePick.ray;
  89599. }
  89600. // always fire the prepointer oversvable
  89601. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  89602. // allow every non pointer down event to flow to the utility layer
  89603. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  89604. if (!prePointerInfo.skipOnPointerObservable) {
  89605. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89606. }
  89607. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  89608. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89609. }
  89610. return;
  89611. }
  89612. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  89613. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  89614. if (utilityScenePick && utilityScenePick.hit) {
  89615. if (!prePointerInfo.skipOnPointerObservable) {
  89616. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89617. }
  89618. prePointerInfo.skipOnPointerObservable = true;
  89619. }
  89620. }
  89621. else {
  89622. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  89623. var pointerEvent_1 = (prePointerInfo.event);
  89624. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  89625. if (originalScenePick && utilityScenePick) {
  89626. // No pick in utility scene
  89627. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  89628. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89629. // We touched an utility mesh present in the main scene
  89630. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89631. prePointerInfo.skipOnPointerObservable = true;
  89632. }
  89633. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89634. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  89635. }
  89636. }
  89637. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  89638. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  89639. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  89640. // If a previous utility layer set this, do not unset this
  89641. if (!prePointerInfo.skipOnPointerObservable) {
  89642. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  89643. }
  89644. }
  89645. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  89646. // We have a pick in both scenes but main is closer than utility
  89647. // We touched an utility mesh present in the main scene
  89648. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89649. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89650. prePointerInfo.skipOnPointerObservable = true;
  89651. }
  89652. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  89653. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  89654. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  89655. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  89656. }
  89657. }
  89658. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  89659. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  89660. }
  89661. }
  89662. }
  89663. });
  89664. // Render directly on top of existing scene without clearing
  89665. this.utilityLayerScene.autoClear = false;
  89666. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  89667. if (_this.shouldRender) {
  89668. _this.render();
  89669. }
  89670. });
  89671. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  89672. _this.dispose();
  89673. });
  89674. this._updateCamera();
  89675. }
  89676. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  89677. /**
  89678. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  89679. */
  89680. get: function () {
  89681. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  89682. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89683. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89684. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89685. });
  89686. }
  89687. return UtilityLayerRenderer._DefaultUtilityLayer;
  89688. },
  89689. enumerable: true,
  89690. configurable: true
  89691. });
  89692. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  89693. /**
  89694. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  89695. */
  89696. get: function () {
  89697. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  89698. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89699. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  89700. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89701. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89702. });
  89703. }
  89704. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  89705. },
  89706. enumerable: true,
  89707. configurable: true
  89708. });
  89709. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  89710. if (!prePointerInfo.skipOnPointerObservable) {
  89711. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  89712. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  89713. }
  89714. };
  89715. /**
  89716. * Renders the utility layers scene on top of the original scene
  89717. */
  89718. UtilityLayerRenderer.prototype.render = function () {
  89719. this._updateCamera();
  89720. if (this.utilityLayerScene.activeCamera) {
  89721. // Set the camera's scene to utility layers scene
  89722. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  89723. var camera = this.utilityLayerScene.activeCamera;
  89724. camera._scene = this.utilityLayerScene;
  89725. if (camera.leftCamera) {
  89726. camera.leftCamera._scene = this.utilityLayerScene;
  89727. }
  89728. if (camera.rightCamera) {
  89729. camera.rightCamera._scene = this.utilityLayerScene;
  89730. }
  89731. this.utilityLayerScene.render(false);
  89732. // Reset camera's scene back to original
  89733. camera._scene = oldScene;
  89734. if (camera.leftCamera) {
  89735. camera.leftCamera._scene = oldScene;
  89736. }
  89737. if (camera.rightCamera) {
  89738. camera.rightCamera._scene = oldScene;
  89739. }
  89740. }
  89741. };
  89742. /**
  89743. * Disposes of the renderer
  89744. */
  89745. UtilityLayerRenderer.prototype.dispose = function () {
  89746. this.onPointerOutObservable.clear();
  89747. if (this._afterRenderObserver) {
  89748. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  89749. }
  89750. if (this._sceneDisposeObserver) {
  89751. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89752. }
  89753. if (this._originalPointerObserver) {
  89754. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  89755. }
  89756. this.utilityLayerScene.dispose();
  89757. };
  89758. UtilityLayerRenderer.prototype._updateCamera = function () {
  89759. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  89760. };
  89761. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89762. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89763. return UtilityLayerRenderer;
  89764. }());
  89765. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  89766. })(BABYLON || (BABYLON = {}));
  89767. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  89768. //# sourceMappingURL=babylon.behavior.js.map
  89769. var BABYLON;
  89770. (function (BABYLON) {
  89771. /**
  89772. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  89773. */
  89774. var PointerDragBehavior = /** @class */ (function () {
  89775. /**
  89776. * Creates a pointer drag behavior that can be attached to a mesh
  89777. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  89778. */
  89779. function PointerDragBehavior(options) {
  89780. /**
  89781. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  89782. */
  89783. this.maxDragAngle = 0;
  89784. /**
  89785. * @hidden
  89786. */
  89787. this._useAlternatePickedPointAboveMaxDragAngle = false;
  89788. /**
  89789. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89790. */
  89791. this.currentDraggingPointerID = -1;
  89792. /**
  89793. * If the behavior is currently in a dragging state
  89794. */
  89795. this.dragging = false;
  89796. /**
  89797. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89798. */
  89799. this.dragDeltaRatio = 0.2;
  89800. /**
  89801. * If the drag plane orientation should be updated during the dragging (Default: true)
  89802. */
  89803. this.updateDragPlane = true;
  89804. // Debug mode will display drag planes to help visualize behavior
  89805. this._debugMode = false;
  89806. this._moving = false;
  89807. /**
  89808. * Fires each time the attached mesh is dragged with the pointer
  89809. * * delta between last drag position and current drag position in world space
  89810. * * dragDistance along the drag axis
  89811. * * dragPlaneNormal normal of the current drag plane used during the drag
  89812. * * dragPlanePoint in world space where the drag intersects the drag plane
  89813. */
  89814. this.onDragObservable = new BABYLON.Observable();
  89815. /**
  89816. * Fires each time a drag begins (eg. mouse down on mesh)
  89817. */
  89818. this.onDragStartObservable = new BABYLON.Observable();
  89819. /**
  89820. * Fires each time a drag ends (eg. mouse release after drag)
  89821. */
  89822. this.onDragEndObservable = new BABYLON.Observable();
  89823. /**
  89824. * If the attached mesh should be moved when dragged
  89825. */
  89826. this.moveAttached = true;
  89827. /**
  89828. * If the drag behavior will react to drag events (Default: true)
  89829. */
  89830. this.enabled = true;
  89831. /**
  89832. * If camera controls should be detached during the drag
  89833. */
  89834. this.detachCameraControls = true;
  89835. /**
  89836. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89837. */
  89838. this.useObjectOrienationForDragging = true;
  89839. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89840. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89841. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89842. // Variables to avoid instantiation in the below method
  89843. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89844. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89845. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89846. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89847. this._lineB = new BABYLON.Vector3(0, 0, 0);
  89848. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  89849. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  89850. this._options = options ? options : {};
  89851. var optionCount = 0;
  89852. if (this._options.dragAxis) {
  89853. optionCount++;
  89854. }
  89855. if (this._options.dragPlaneNormal) {
  89856. optionCount++;
  89857. }
  89858. if (optionCount > 1) {
  89859. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89860. }
  89861. }
  89862. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89863. /**
  89864. * The name of the behavior
  89865. */
  89866. get: function () {
  89867. return "PointerDrag";
  89868. },
  89869. enumerable: true,
  89870. configurable: true
  89871. });
  89872. /**
  89873. * Initializes the behavior
  89874. */
  89875. PointerDragBehavior.prototype.init = function () { };
  89876. /**
  89877. * Attaches the drag behavior the passed in mesh
  89878. * @param ownerNode The mesh that will be dragged around once attached
  89879. */
  89880. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89881. var _this = this;
  89882. this._scene = ownerNode.getScene();
  89883. this._attachedNode = ownerNode;
  89884. // Initialize drag plane to not interfere with existing scene
  89885. if (!PointerDragBehavior._planeScene) {
  89886. if (this._debugMode) {
  89887. PointerDragBehavior._planeScene = this._scene;
  89888. }
  89889. else {
  89890. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89891. PointerDragBehavior._planeScene.detachControl();
  89892. this._scene.getEngine().scenes.pop();
  89893. this._scene.onDisposeObservable.addOnce(function () {
  89894. PointerDragBehavior._planeScene.dispose();
  89895. PointerDragBehavior._planeScene = null;
  89896. });
  89897. }
  89898. }
  89899. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89900. // State of the drag
  89901. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89902. var delta = new BABYLON.Vector3(0, 0, 0);
  89903. var dragLength = 0;
  89904. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89905. var pickPredicate = function (m) {
  89906. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89907. };
  89908. var attachedElement = null;
  89909. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89910. if (!_this.enabled) {
  89911. return;
  89912. }
  89913. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89914. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89915. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89916. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89917. if (pickedPoint) {
  89918. _this.dragging = true;
  89919. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89920. _this.lastDragPosition.copyFrom(pickedPoint);
  89921. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89922. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89923. // Detatch camera controls
  89924. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89925. if (_this._scene.activeCamera.inputs.attachedElement) {
  89926. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89927. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89928. }
  89929. else {
  89930. attachedElement = null;
  89931. }
  89932. }
  89933. }
  89934. }
  89935. }
  89936. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89937. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89938. _this.releaseDrag();
  89939. // Reattach camera controls
  89940. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89941. _this._scene.activeCamera.attachControl(attachedElement, true);
  89942. }
  89943. }
  89944. }
  89945. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89946. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89947. _this._moving = true;
  89948. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89949. if (pickedPoint) {
  89950. if (_this.updateDragPlane) {
  89951. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89952. }
  89953. // depending on the drag mode option drag accordingly
  89954. if (_this._options.dragAxis) {
  89955. // Convert local drag axis to world
  89956. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89957. // Project delta drag from the drag plane onto the drag axis
  89958. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89959. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89960. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89961. }
  89962. else {
  89963. dragLength = delta.length();
  89964. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89965. }
  89966. targetPosition.addInPlace(delta);
  89967. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89968. _this.lastDragPosition.copyFrom(pickedPoint);
  89969. }
  89970. }
  89971. }
  89972. });
  89973. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89974. if (_this._moving && _this.moveAttached) {
  89975. // Slowly move mesh to avoid jitter
  89976. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89977. _this._tmpVector.scaleInPlace(0.2);
  89978. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89979. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89980. }
  89981. });
  89982. };
  89983. PointerDragBehavior.prototype.releaseDrag = function () {
  89984. this.dragging = false;
  89985. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89986. this.currentDraggingPointerID = -1;
  89987. this._moving = false;
  89988. };
  89989. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89990. var _this = this;
  89991. if (!ray) {
  89992. return null;
  89993. }
  89994. // Calculate angle between plane normal and ray
  89995. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89996. // Correct if ray is casted from oposite side
  89997. if (angle > Math.PI / 2) {
  89998. angle = Math.PI - angle;
  89999. }
  90000. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  90001. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  90002. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  90003. // Invert ray direction along the towards object axis
  90004. this._tmpVector.copyFrom(ray.direction);
  90005. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  90006. this._alternatePickedPoint.normalize();
  90007. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  90008. this._tmpVector.addInPlace(this._alternatePickedPoint);
  90009. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  90010. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  90011. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  90012. this._alternatePickedPoint.addInPlace(this._tmpVector);
  90013. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  90014. return this._alternatePickedPoint;
  90015. }
  90016. else {
  90017. return null;
  90018. }
  90019. }
  90020. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  90021. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  90022. return pickResult.pickedPoint;
  90023. }
  90024. else {
  90025. return null;
  90026. }
  90027. };
  90028. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  90029. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  90030. this._pointA.copyFrom(dragPlanePosition);
  90031. if (this._options.dragAxis) {
  90032. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  90033. // Calculate plane normal in direction of camera but perpendicular to drag axis
  90034. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  90035. ray.origin.subtractToRef(this._pointA, this._pointC);
  90036. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  90037. // Get perpendicular line from direction to camera and drag axis
  90038. this._pointB.subtractToRef(this._pointA, this._lineA);
  90039. this._pointC.subtractToRef(this._pointA, this._lineB);
  90040. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  90041. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  90042. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  90043. this._lookAt.normalize();
  90044. this._dragPlane.position.copyFrom(this._pointA);
  90045. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  90046. this._dragPlane.lookAt(this._lookAt);
  90047. }
  90048. else if (this._options.dragPlaneNormal) {
  90049. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  90050. this._dragPlane.position.copyFrom(this._pointA);
  90051. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  90052. this._dragPlane.lookAt(this._lookAt);
  90053. }
  90054. else {
  90055. this._dragPlane.position.copyFrom(this._pointA);
  90056. this._dragPlane.lookAt(ray.origin);
  90057. }
  90058. this._dragPlane.computeWorldMatrix(true);
  90059. };
  90060. /**
  90061. * Detaches the behavior from the mesh
  90062. */
  90063. PointerDragBehavior.prototype.detach = function () {
  90064. if (this._pointerObserver) {
  90065. this._scene.onPointerObservable.remove(this._pointerObserver);
  90066. }
  90067. if (this._beforeRenderObserver) {
  90068. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90069. }
  90070. };
  90071. return PointerDragBehavior;
  90072. }());
  90073. BABYLON.PointerDragBehavior = PointerDragBehavior;
  90074. })(BABYLON || (BABYLON = {}));
  90075. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  90076. var BABYLON;
  90077. (function (BABYLON) {
  90078. /**
  90079. * A behavior that when attached to a mesh will allow the mesh to be scaled
  90080. */
  90081. var MultiPointerScaleBehavior = /** @class */ (function () {
  90082. function MultiPointerScaleBehavior() {
  90083. this._startDistance = 0;
  90084. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  90085. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  90086. this._sceneRenderObserver = null;
  90087. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  90088. this._dragBehaviorA.moveAttached = false;
  90089. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  90090. this._dragBehaviorB.moveAttached = false;
  90091. }
  90092. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  90093. /**
  90094. * The name of the behavior
  90095. */
  90096. get: function () {
  90097. return "MultiPointerScale";
  90098. },
  90099. enumerable: true,
  90100. configurable: true
  90101. });
  90102. /**
  90103. * Initializes the behavior
  90104. */
  90105. MultiPointerScaleBehavior.prototype.init = function () { };
  90106. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  90107. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  90108. };
  90109. /**
  90110. * Attaches the scale behavior the passed in mesh
  90111. * @param ownerNode The mesh that will be scaled around once attached
  90112. */
  90113. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  90114. var _this = this;
  90115. this._ownerNode = ownerNode;
  90116. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  90117. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  90118. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90119. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90120. _this._dragBehaviorA.releaseDrag();
  90121. }
  90122. else {
  90123. _this._initialScale.copyFrom(ownerNode.scaling);
  90124. _this._startDistance = _this._getCurrentDistance();
  90125. }
  90126. }
  90127. });
  90128. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  90129. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90130. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90131. _this._dragBehaviorB.releaseDrag();
  90132. }
  90133. else {
  90134. _this._initialScale.copyFrom(ownerNode.scaling);
  90135. _this._startDistance = _this._getCurrentDistance();
  90136. }
  90137. }
  90138. });
  90139. // Once both drag behaviors are active scale based on the distance between the two pointers
  90140. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90141. behavior.onDragObservable.add(function () {
  90142. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90143. var ratio = _this._getCurrentDistance() / _this._startDistance;
  90144. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  90145. }
  90146. });
  90147. });
  90148. ownerNode.addBehavior(this._dragBehaviorA);
  90149. ownerNode.addBehavior(this._dragBehaviorB);
  90150. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90151. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90152. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90153. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  90154. if (change.length() > 0.01) {
  90155. ownerNode.scaling.addInPlace(change);
  90156. }
  90157. }
  90158. });
  90159. };
  90160. /**
  90161. * Detaches the behavior from the mesh
  90162. */
  90163. MultiPointerScaleBehavior.prototype.detach = function () {
  90164. var _this = this;
  90165. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90166. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90167. behavior.onDragStartObservable.clear();
  90168. behavior.onDragObservable.clear();
  90169. _this._ownerNode.removeBehavior(behavior);
  90170. });
  90171. };
  90172. return MultiPointerScaleBehavior;
  90173. }());
  90174. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  90175. })(BABYLON || (BABYLON = {}));
  90176. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  90177. var BABYLON;
  90178. (function (BABYLON) {
  90179. /**
  90180. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  90181. */
  90182. var SixDofDragBehavior = /** @class */ (function () {
  90183. function SixDofDragBehavior() {
  90184. this._sceneRenderObserver = null;
  90185. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  90186. this._moving = false;
  90187. this._startingOrientation = new BABYLON.Quaternion();
  90188. /**
  90189. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  90190. */
  90191. this.zDragFactor = 3;
  90192. /**
  90193. * If the behavior is currently in a dragging state
  90194. */
  90195. this.dragging = false;
  90196. /**
  90197. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  90198. */
  90199. this.dragDeltaRatio = 0.2;
  90200. /**
  90201. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  90202. */
  90203. this.currentDraggingPointerID = -1;
  90204. /**
  90205. * If camera controls should be detached during the drag
  90206. */
  90207. this.detachCameraControls = true;
  90208. }
  90209. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  90210. /**
  90211. * The name of the behavior
  90212. */
  90213. get: function () {
  90214. return "SixDofDrag";
  90215. },
  90216. enumerable: true,
  90217. configurable: true
  90218. });
  90219. /**
  90220. * Initializes the behavior
  90221. */
  90222. SixDofDragBehavior.prototype.init = function () { };
  90223. /**
  90224. * Attaches the scale behavior the passed in mesh
  90225. * @param ownerNode The mesh that will be scaled around once attached
  90226. */
  90227. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  90228. var _this = this;
  90229. this._ownerNode = ownerNode;
  90230. this._scene = this._ownerNode.getScene();
  90231. if (!SixDofDragBehavior._virtualScene) {
  90232. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  90233. this._scene.getEngine().scenes.pop();
  90234. }
  90235. var pickedMesh = null;
  90236. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  90237. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  90238. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  90239. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  90240. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  90241. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  90242. var pickPredicate = function (m) {
  90243. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  90244. };
  90245. var attachedElement = null;
  90246. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  90247. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90248. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  90249. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  90250. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  90251. }
  90252. pickedMesh = _this._ownerNode;
  90253. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  90254. // Set position and orientation of the controller
  90255. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  90256. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  90257. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  90258. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90259. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  90260. if (!pickedMesh.rotationQuaternion) {
  90261. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  90262. }
  90263. var oldParent = pickedMesh.parent;
  90264. pickedMesh.setParent(null);
  90265. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  90266. pickedMesh.setParent(oldParent);
  90267. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  90268. // Update state
  90269. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  90270. _this.dragging = true;
  90271. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  90272. // Detatch camera controls
  90273. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90274. if (_this._scene.activeCamera.inputs.attachedElement) {
  90275. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  90276. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  90277. }
  90278. else {
  90279. attachedElement = null;
  90280. }
  90281. }
  90282. }
  90283. }
  90284. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  90285. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  90286. _this.dragging = false;
  90287. _this._moving = false;
  90288. _this.currentDraggingPointerID = -1;
  90289. pickedMesh = null;
  90290. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90291. // Reattach camera controls
  90292. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90293. _this._scene.activeCamera.attachControl(attachedElement, true);
  90294. }
  90295. }
  90296. }
  90297. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  90298. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  90299. var zDragFactor = _this.zDragFactor;
  90300. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  90301. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  90302. zDragFactor = 0;
  90303. }
  90304. // Calculate controller drag distance in controller space
  90305. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  90306. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  90307. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  90308. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  90309. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  90310. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  90311. if (_this._virtualDragMesh.position.z < 0) {
  90312. _this._virtualDragMesh.position.z = 0;
  90313. }
  90314. // Update the controller position
  90315. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  90316. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  90317. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90318. // Move the virtualObjectsPosition into the picked mesh's space if needed
  90319. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  90320. if (pickedMesh.parent) {
  90321. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  90322. }
  90323. if (!_this._moving) {
  90324. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  90325. }
  90326. _this._moving = true;
  90327. }
  90328. }
  90329. });
  90330. var tmpQuaternion = new BABYLON.Quaternion();
  90331. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90332. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90333. if (_this.dragging && _this._moving && pickedMesh) {
  90334. // Slowly move mesh to avoid jitter
  90335. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  90336. // Get change in rotation
  90337. tmpQuaternion.copyFrom(_this._startingOrientation);
  90338. tmpQuaternion.x = -tmpQuaternion.x;
  90339. tmpQuaternion.y = -tmpQuaternion.y;
  90340. tmpQuaternion.z = -tmpQuaternion.z;
  90341. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  90342. // Convert change in rotation to only y axis rotation
  90343. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  90344. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  90345. // Slowly move mesh to avoid jitter
  90346. var oldParent = pickedMesh.parent;
  90347. pickedMesh.setParent(null);
  90348. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  90349. pickedMesh.setParent(oldParent);
  90350. }
  90351. });
  90352. };
  90353. /**
  90354. * Detaches the behavior from the mesh
  90355. */
  90356. SixDofDragBehavior.prototype.detach = function () {
  90357. if (this._scene) {
  90358. this._scene.onPointerObservable.remove(this._pointerObserver);
  90359. }
  90360. if (this._ownerNode) {
  90361. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90362. }
  90363. if (this._virtualOriginMesh) {
  90364. this._virtualOriginMesh.dispose();
  90365. }
  90366. if (this._virtualDragMesh) {
  90367. this._virtualDragMesh.dispose();
  90368. }
  90369. };
  90370. return SixDofDragBehavior;
  90371. }());
  90372. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  90373. })(BABYLON || (BABYLON = {}));
  90374. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  90375. var BABYLON;
  90376. (function (BABYLON) {
  90377. /**
  90378. * @hidden
  90379. */
  90380. var FaceDirectionInfo = /** @class */ (function () {
  90381. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  90382. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  90383. if (diff === void 0) { diff = 0; }
  90384. if (ignore === void 0) { ignore = false; }
  90385. this.direction = direction;
  90386. this.rotatedDirection = rotatedDirection;
  90387. this.diff = diff;
  90388. this.ignore = ignore;
  90389. }
  90390. return FaceDirectionInfo;
  90391. }());
  90392. /**
  90393. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  90394. */
  90395. var AttachToBoxBehavior = /** @class */ (function () {
  90396. /**
  90397. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  90398. * @param ui The transform node that should be attched to the mesh
  90399. */
  90400. function AttachToBoxBehavior(ui) {
  90401. this.ui = ui;
  90402. /**
  90403. * The name of the behavior
  90404. */
  90405. this.name = "AttachToBoxBehavior";
  90406. /**
  90407. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  90408. */
  90409. this.distanceAwayFromFace = 0.15;
  90410. /**
  90411. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  90412. */
  90413. this.distanceAwayFromBottomOfFace = 0.15;
  90414. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  90415. this._tmpMatrix = new BABYLON.Matrix();
  90416. this._tmpVector = new BABYLON.Vector3();
  90417. this._zeroVector = BABYLON.Vector3.Zero();
  90418. this._lookAtTmpMatrix = new BABYLON.Matrix();
  90419. /* Does nothing */
  90420. }
  90421. /**
  90422. * Initializes the behavior
  90423. */
  90424. AttachToBoxBehavior.prototype.init = function () {
  90425. /* Does nothing */
  90426. };
  90427. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  90428. var _this = this;
  90429. // Go over each face and calculate the angle between the face's normal and targetDirection
  90430. this._faceVectors.forEach(function (v) {
  90431. if (!_this._target.rotationQuaternion) {
  90432. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  90433. }
  90434. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  90435. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  90436. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  90437. });
  90438. // Return the face information of the one with the normal closeset to target direction
  90439. return this._faceVectors.reduce(function (min, p) {
  90440. if (min.ignore) {
  90441. return p;
  90442. }
  90443. else if (p.ignore) {
  90444. return min;
  90445. }
  90446. else {
  90447. return min.diff < p.diff ? min : p;
  90448. }
  90449. }, this._faceVectors[0]);
  90450. };
  90451. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  90452. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  90453. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  90454. this._lookAtTmpMatrix.invert();
  90455. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  90456. };
  90457. /**
  90458. * Attaches the AttachToBoxBehavior to the passed in mesh
  90459. * @param target The mesh that the specified node will be attached to
  90460. */
  90461. AttachToBoxBehavior.prototype.attach = function (target) {
  90462. var _this = this;
  90463. this._target = target;
  90464. this._scene = this._target.getScene();
  90465. // Every frame, update the app bars position
  90466. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  90467. if (!_this._scene.activeCamera) {
  90468. return;
  90469. }
  90470. // Find the face closest to the cameras position
  90471. var cameraPos = _this._scene.activeCamera.position;
  90472. if (_this._scene.activeCamera.devicePosition) {
  90473. cameraPos = _this._scene.activeCamera.devicePosition;
  90474. }
  90475. var facing = _this._closestFace(cameraPos.subtract(target.position));
  90476. if (_this._scene.activeCamera.leftCamera) {
  90477. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90478. }
  90479. else {
  90480. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90481. }
  90482. // Get camera up direction
  90483. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  90484. // Ignore faces to not select a parrelel face for the up vector of the UI
  90485. _this._faceVectors.forEach(function (v) {
  90486. if (facing.direction.x && v.direction.x) {
  90487. v.ignore = true;
  90488. }
  90489. if (facing.direction.y && v.direction.y) {
  90490. v.ignore = true;
  90491. }
  90492. if (facing.direction.z && v.direction.z) {
  90493. v.ignore = true;
  90494. }
  90495. });
  90496. var facingUp = _this._closestFace(_this._tmpVector);
  90497. // Unignore faces
  90498. _this._faceVectors.forEach(function (v) {
  90499. v.ignore = false;
  90500. });
  90501. // Position the app bar on that face
  90502. _this.ui.position.copyFrom(target.position);
  90503. if (facing.direction.x) {
  90504. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90505. _this.ui.position.addInPlace(_this._tmpVector);
  90506. }
  90507. if (facing.direction.y) {
  90508. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90509. _this.ui.position.addInPlace(_this._tmpVector);
  90510. }
  90511. if (facing.direction.z) {
  90512. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90513. _this.ui.position.addInPlace(_this._tmpVector);
  90514. }
  90515. // Rotate to be oriented properly to the camera
  90516. if (!_this.ui.rotationQuaternion) {
  90517. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  90518. }
  90519. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  90520. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  90521. // Place ui the correct distance from the bottom of the mesh
  90522. if (facingUp.direction.x) {
  90523. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  90524. }
  90525. if (facingUp.direction.y) {
  90526. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  90527. }
  90528. if (facingUp.direction.z) {
  90529. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  90530. }
  90531. _this.ui.position.addInPlace(_this._tmpVector);
  90532. });
  90533. };
  90534. /**
  90535. * Detaches the behavior from the mesh
  90536. */
  90537. AttachToBoxBehavior.prototype.detach = function () {
  90538. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  90539. };
  90540. return AttachToBoxBehavior;
  90541. }());
  90542. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  90543. })(BABYLON || (BABYLON = {}));
  90544. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  90545. var BABYLON;
  90546. (function (BABYLON) {
  90547. /**
  90548. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  90549. */
  90550. var Gizmo = /** @class */ (function () {
  90551. /**
  90552. * Creates a gizmo
  90553. * @param gizmoLayer The utility layer the gizmo will be added to
  90554. */
  90555. function Gizmo(
  90556. /** The utility layer the gizmo will be added to */
  90557. gizmoLayer) {
  90558. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90559. var _this = this;
  90560. this.gizmoLayer = gizmoLayer;
  90561. this._scaleFactor = 3;
  90562. this._tmpMatrix = new BABYLON.Matrix();
  90563. /**
  90564. * If a custom mesh has been set (Default: false)
  90565. */
  90566. this._customMeshSet = false;
  90567. /**
  90568. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  90569. */
  90570. this.updateGizmoRotationToMatchAttachedMesh = true;
  90571. /**
  90572. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  90573. */
  90574. this.updateGizmoPositionToMatchAttachedMesh = true;
  90575. /**
  90576. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  90577. */
  90578. this._updateScale = true;
  90579. this._interactionsEnabled = true;
  90580. this._tempVector = new BABYLON.Vector3();
  90581. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  90582. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  90583. _this._update();
  90584. });
  90585. this.attachedMesh = null;
  90586. }
  90587. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  90588. /**
  90589. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  90590. * * When set, interactions will be enabled
  90591. */
  90592. get: function () {
  90593. return this._attachedMesh;
  90594. },
  90595. set: function (value) {
  90596. this._attachedMesh = value;
  90597. this._rootMesh.setEnabled(value ? true : false);
  90598. this._attachedMeshChanged(value);
  90599. },
  90600. enumerable: true,
  90601. configurable: true
  90602. });
  90603. /**
  90604. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  90605. * @param mesh The mesh to replace the default mesh of the gizmo
  90606. */
  90607. Gizmo.prototype.setCustomMesh = function (mesh) {
  90608. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  90609. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  90610. }
  90611. this._rootMesh.getChildMeshes().forEach(function (c) {
  90612. c.dispose();
  90613. });
  90614. mesh.parent = this._rootMesh;
  90615. this._customMeshSet = true;
  90616. };
  90617. Gizmo.prototype._attachedMeshChanged = function (value) {
  90618. };
  90619. /**
  90620. * @hidden
  90621. * Updates the gizmo to match the attached mesh's position/rotation
  90622. */
  90623. Gizmo.prototype._update = function () {
  90624. if (this.attachedMesh) {
  90625. if (this.updateGizmoRotationToMatchAttachedMesh) {
  90626. if (!this._rootMesh.rotationQuaternion) {
  90627. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  90628. }
  90629. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  90630. this._tempVector.copyFrom(this.attachedMesh.scaling);
  90631. if (this.attachedMesh.scaling.x < 0) {
  90632. this.attachedMesh.scaling.x *= -1;
  90633. }
  90634. if (this.attachedMesh.scaling.y < 0) {
  90635. this.attachedMesh.scaling.y *= -1;
  90636. }
  90637. if (this.attachedMesh.scaling.z < 0) {
  90638. this.attachedMesh.scaling.z *= -1;
  90639. }
  90640. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  90641. this.attachedMesh.scaling.copyFrom(this._tempVector);
  90642. this.attachedMesh.computeWorldMatrix();
  90643. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  90644. }
  90645. if (this.updateGizmoPositionToMatchAttachedMesh) {
  90646. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  90647. }
  90648. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  90649. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  90650. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  90651. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  90652. }
  90653. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  90654. var dist = this._tempVector.length() / this._scaleFactor;
  90655. this._rootMesh.scaling.set(dist, dist, dist);
  90656. }
  90657. }
  90658. };
  90659. /**
  90660. * Disposes of the gizmo
  90661. */
  90662. Gizmo.prototype.dispose = function () {
  90663. this._rootMesh.dispose();
  90664. if (this._beforeRenderObserver) {
  90665. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90666. }
  90667. };
  90668. return Gizmo;
  90669. }());
  90670. BABYLON.Gizmo = Gizmo;
  90671. })(BABYLON || (BABYLON = {}));
  90672. //# sourceMappingURL=babylon.gizmo.js.map
  90673. var BABYLON;
  90674. (function (BABYLON) {
  90675. /**
  90676. * Single axis drag gizmo
  90677. */
  90678. var AxisDragGizmo = /** @class */ (function (_super) {
  90679. __extends(AxisDragGizmo, _super);
  90680. /**
  90681. * Creates an AxisDragGizmo
  90682. * @param gizmoLayer The utility layer the gizmo will be added to
  90683. * @param dragAxis The axis which the gizmo will be able to drag on
  90684. * @param color The color of the gizmo
  90685. */
  90686. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  90687. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90688. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90689. var _this = _super.call(this, gizmoLayer) || this;
  90690. _this._pointerObserver = null;
  90691. /**
  90692. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90693. */
  90694. _this.snapDistance = 0;
  90695. /**
  90696. * Event that fires each time the gizmo snaps to a new location.
  90697. * * snapDistance is the the change in distance
  90698. */
  90699. _this.onSnapObservable = new BABYLON.Observable();
  90700. // Create Material
  90701. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90702. coloredMaterial.disableLighting = true;
  90703. coloredMaterial.emissiveColor = color;
  90704. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90705. hoverMaterial.disableLighting = true;
  90706. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90707. // Build mesh on root node
  90708. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90709. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90710. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90711. arrowTail.color = coloredMaterial.emissiveColor;
  90712. arrow.addChild(arrowMesh);
  90713. arrow.addChild(arrowTail);
  90714. // Position arrow pointing in its drag axis
  90715. arrowMesh.scaling.scaleInPlace(0.05);
  90716. arrowMesh.material = coloredMaterial;
  90717. arrowMesh.rotation.x = Math.PI / 2;
  90718. arrowMesh.position.z += 0.3;
  90719. arrowTail.scaling.scaleInPlace(0.2);
  90720. arrowTail.rotation.x = Math.PI / 2;
  90721. arrowTail.material = coloredMaterial;
  90722. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90723. _this._rootMesh.addChild(arrow);
  90724. var currentSnapDragDistance = 0;
  90725. var tmpVector = new BABYLON.Vector3();
  90726. var tmpSnapEvent = { snapDistance: 0 };
  90727. // Add drag behavior to handle events when the gizmo is dragged
  90728. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90729. _this.dragBehavior.moveAttached = false;
  90730. _this._rootMesh.addBehavior(_this.dragBehavior);
  90731. _this.dragBehavior.onDragObservable.add(function (event) {
  90732. if (_this.attachedMesh) {
  90733. // Snapping logic
  90734. if (_this.snapDistance == 0) {
  90735. _this.attachedMesh.position.addInPlace(event.delta);
  90736. }
  90737. else {
  90738. currentSnapDragDistance += event.dragDistance;
  90739. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90740. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  90741. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90742. event.delta.normalizeToRef(tmpVector);
  90743. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  90744. _this.attachedMesh.position.addInPlace(tmpVector);
  90745. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90746. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90747. }
  90748. }
  90749. }
  90750. });
  90751. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90752. if (_this._customMeshSet) {
  90753. return;
  90754. }
  90755. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90756. var material = isHovered ? hoverMaterial : coloredMaterial;
  90757. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90758. m.material = material;
  90759. if (m.color) {
  90760. m.color = material.emissiveColor;
  90761. }
  90762. });
  90763. });
  90764. return _this;
  90765. }
  90766. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  90767. if (this.dragBehavior) {
  90768. this.dragBehavior.enabled = value ? true : false;
  90769. }
  90770. };
  90771. /**
  90772. * Disposes of the gizmo
  90773. */
  90774. AxisDragGizmo.prototype.dispose = function () {
  90775. this.onSnapObservable.clear();
  90776. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90777. this.dragBehavior.detach();
  90778. _super.prototype.dispose.call(this);
  90779. };
  90780. return AxisDragGizmo;
  90781. }(BABYLON.Gizmo));
  90782. BABYLON.AxisDragGizmo = AxisDragGizmo;
  90783. })(BABYLON || (BABYLON = {}));
  90784. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  90785. var BABYLON;
  90786. (function (BABYLON) {
  90787. /**
  90788. * Single axis scale gizmo
  90789. */
  90790. var AxisScaleGizmo = /** @class */ (function (_super) {
  90791. __extends(AxisScaleGizmo, _super);
  90792. /**
  90793. * Creates an AxisScaleGizmo
  90794. * @param gizmoLayer The utility layer the gizmo will be added to
  90795. * @param dragAxis The axis which the gizmo will be able to scale on
  90796. * @param color The color of the gizmo
  90797. */
  90798. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  90799. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90800. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90801. var _this = _super.call(this, gizmoLayer) || this;
  90802. _this._pointerObserver = null;
  90803. /**
  90804. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90805. */
  90806. _this.snapDistance = 0;
  90807. /**
  90808. * Event that fires each time the gizmo snaps to a new location.
  90809. * * snapDistance is the the change in distance
  90810. */
  90811. _this.onSnapObservable = new BABYLON.Observable();
  90812. // Create Material
  90813. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90814. coloredMaterial.disableLighting = true;
  90815. coloredMaterial.emissiveColor = color;
  90816. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90817. hoverMaterial.disableLighting = true;
  90818. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90819. // Build mesh on root node
  90820. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90821. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  90822. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90823. arrowTail.color = coloredMaterial.emissiveColor;
  90824. arrow.addChild(arrowMesh);
  90825. arrow.addChild(arrowTail);
  90826. // Position arrow pointing in its drag axis
  90827. arrowMesh.scaling.scaleInPlace(0.1);
  90828. arrowMesh.material = coloredMaterial;
  90829. arrowMesh.rotation.x = Math.PI / 2;
  90830. arrowMesh.position.z += 0.3;
  90831. arrowTail.scaling.scaleInPlace(0.2);
  90832. arrowTail.rotation.x = Math.PI / 2;
  90833. arrowTail.material = coloredMaterial;
  90834. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90835. _this._rootMesh.addChild(arrow);
  90836. // Add drag behavior to handle events when the gizmo is dragged
  90837. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90838. _this.dragBehavior.moveAttached = false;
  90839. _this._rootMesh.addBehavior(_this.dragBehavior);
  90840. var currentSnapDragDistance = 0;
  90841. var tmpVector = new BABYLON.Vector3();
  90842. var tmpSnapEvent = { snapDistance: 0 };
  90843. _this.dragBehavior.onDragObservable.add(function (event) {
  90844. if (_this.attachedMesh) {
  90845. // Snapping logic
  90846. var snapped = false;
  90847. var dragSteps = 0;
  90848. if (_this.snapDistance == 0) {
  90849. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  90850. }
  90851. else {
  90852. currentSnapDragDistance += event.dragDistance;
  90853. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90854. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90855. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90856. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  90857. snapped = true;
  90858. }
  90859. else {
  90860. tmpVector.scaleInPlace(0);
  90861. }
  90862. }
  90863. _this.attachedMesh.scaling.addInPlace(tmpVector);
  90864. if (snapped) {
  90865. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90866. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90867. }
  90868. }
  90869. });
  90870. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90871. if (_this._customMeshSet) {
  90872. return;
  90873. }
  90874. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90875. var material = isHovered ? hoverMaterial : coloredMaterial;
  90876. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90877. m.material = material;
  90878. if (m.color) {
  90879. m.color = material.emissiveColor;
  90880. }
  90881. });
  90882. });
  90883. return _this;
  90884. }
  90885. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  90886. if (this.dragBehavior) {
  90887. this.dragBehavior.enabled = value ? true : false;
  90888. }
  90889. };
  90890. /**
  90891. * Disposes of the gizmo
  90892. */
  90893. AxisScaleGizmo.prototype.dispose = function () {
  90894. this.onSnapObservable.clear();
  90895. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90896. this.dragBehavior.detach();
  90897. _super.prototype.dispose.call(this);
  90898. };
  90899. return AxisScaleGizmo;
  90900. }(BABYLON.Gizmo));
  90901. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  90902. })(BABYLON || (BABYLON = {}));
  90903. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  90904. var BABYLON;
  90905. (function (BABYLON) {
  90906. /**
  90907. * Single plane rotation gizmo
  90908. */
  90909. var PlaneRotationGizmo = /** @class */ (function (_super) {
  90910. __extends(PlaneRotationGizmo, _super);
  90911. /**
  90912. * Creates a PlaneRotationGizmo
  90913. * @param gizmoLayer The utility layer the gizmo will be added to
  90914. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  90915. * @param color The color of the gizmo
  90916. */
  90917. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  90918. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90919. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90920. var _this = _super.call(this, gizmoLayer) || this;
  90921. _this._pointerObserver = null;
  90922. /**
  90923. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  90924. */
  90925. _this.snapDistance = 0;
  90926. /**
  90927. * Event that fires each time the gizmo snaps to a new location.
  90928. * * snapDistance is the the change in distance
  90929. */
  90930. _this.onSnapObservable = new BABYLON.Observable();
  90931. // Create Material
  90932. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90933. coloredMaterial.disableLighting = true;
  90934. coloredMaterial.emissiveColor = color;
  90935. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90936. hoverMaterial.disableLighting = true;
  90937. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90938. // Build mesh on root node
  90939. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90940. // Create circle out of lines
  90941. var tessellation = 20;
  90942. var radius = 2;
  90943. var points = new Array();
  90944. for (var i = 0; i < tessellation; i++) {
  90945. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  90946. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  90947. }
  90948. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  90949. rotationMesh.color = coloredMaterial.emissiveColor;
  90950. // Position arrow pointing in its drag axis
  90951. rotationMesh.scaling.scaleInPlace(0.1);
  90952. rotationMesh.material = coloredMaterial;
  90953. rotationMesh.rotation.x = Math.PI / 2;
  90954. parentMesh.addChild(rotationMesh);
  90955. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  90956. _this._rootMesh.addChild(parentMesh);
  90957. // Add drag behavior to handle events when the gizmo is dragged
  90958. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  90959. _this.dragBehavior.moveAttached = false;
  90960. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  90961. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  90962. _this._rootMesh.addBehavior(_this.dragBehavior);
  90963. var lastDragPosition = new BABYLON.Vector3();
  90964. _this.dragBehavior.onDragStartObservable.add(function (e) {
  90965. if (_this.attachedMesh) {
  90966. lastDragPosition.copyFrom(e.dragPlanePoint);
  90967. }
  90968. });
  90969. var rotationMatrix = new BABYLON.Matrix();
  90970. var planeNormalTowardsCamera = new BABYLON.Vector3();
  90971. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  90972. var tmpSnapEvent = { snapDistance: 0 };
  90973. var currentSnapDragDistance = 0;
  90974. _this.dragBehavior.onDragObservable.add(function (event) {
  90975. if (_this.attachedMesh) {
  90976. if (!_this.attachedMesh.rotationQuaternion) {
  90977. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90978. }
  90979. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  90980. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  90981. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  90982. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  90983. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  90984. var angle = Math.atan2(cross.length(), dot);
  90985. planeNormalTowardsCamera.copyFrom(planeNormal);
  90986. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  90987. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90988. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  90989. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  90990. }
  90991. // Flip up vector depending on which side the camera is on
  90992. if (gizmoLayer.utilityLayerScene.activeCamera) {
  90993. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  90994. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  90995. planeNormalTowardsCamera.scaleInPlace(-1);
  90996. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  90997. }
  90998. }
  90999. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  91000. if (halfCircleSide)
  91001. angle = -angle;
  91002. // Snapping logic
  91003. var snapped = false;
  91004. if (_this.snapDistance != 0) {
  91005. currentSnapDragDistance += angle;
  91006. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91007. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  91008. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91009. angle = _this.snapDistance * dragSteps;
  91010. snapped = true;
  91011. }
  91012. else {
  91013. angle = 0;
  91014. }
  91015. }
  91016. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  91017. var quaternionCoefficient = Math.sin(angle / 2);
  91018. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  91019. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  91020. // Rotate selected mesh quaternion over fixed axis
  91021. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  91022. }
  91023. else {
  91024. // Rotate selected mesh quaternion over rotated axis
  91025. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  91026. }
  91027. lastDragPosition.copyFrom(event.dragPlanePoint);
  91028. if (snapped) {
  91029. tmpSnapEvent.snapDistance = angle;
  91030. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91031. }
  91032. }
  91033. });
  91034. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91035. if (_this._customMeshSet) {
  91036. return;
  91037. }
  91038. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91039. var material = isHovered ? hoverMaterial : coloredMaterial;
  91040. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91041. m.material = material;
  91042. if (m.color) {
  91043. m.color = material.emissiveColor;
  91044. }
  91045. });
  91046. });
  91047. return _this;
  91048. }
  91049. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  91050. if (this.dragBehavior) {
  91051. this.dragBehavior.enabled = value ? true : false;
  91052. }
  91053. };
  91054. /**
  91055. * Disposes of the gizmo
  91056. */
  91057. PlaneRotationGizmo.prototype.dispose = function () {
  91058. this.onSnapObservable.clear();
  91059. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91060. this.dragBehavior.detach();
  91061. _super.prototype.dispose.call(this);
  91062. };
  91063. return PlaneRotationGizmo;
  91064. }(BABYLON.Gizmo));
  91065. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  91066. })(BABYLON || (BABYLON = {}));
  91067. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  91068. var BABYLON;
  91069. (function (BABYLON) {
  91070. /**
  91071. * Gizmo that enables dragging a mesh along 3 axis
  91072. */
  91073. var PositionGizmo = /** @class */ (function (_super) {
  91074. __extends(PositionGizmo, _super);
  91075. /**
  91076. * Creates a PositionGizmo
  91077. * @param gizmoLayer The utility layer the gizmo will be added to
  91078. */
  91079. function PositionGizmo(gizmoLayer) {
  91080. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91081. var _this = _super.call(this, gizmoLayer) || this;
  91082. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91083. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91084. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91085. _this.attachedMesh = null;
  91086. return _this;
  91087. }
  91088. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  91089. set: function (mesh) {
  91090. if (this.xGizmo) {
  91091. this.xGizmo.attachedMesh = mesh;
  91092. this.yGizmo.attachedMesh = mesh;
  91093. this.zGizmo.attachedMesh = mesh;
  91094. }
  91095. },
  91096. enumerable: true,
  91097. configurable: true
  91098. });
  91099. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91100. get: function () {
  91101. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91102. },
  91103. set: function (value) {
  91104. if (this.xGizmo) {
  91105. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91106. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91107. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91108. }
  91109. },
  91110. enumerable: true,
  91111. configurable: true
  91112. });
  91113. /**
  91114. * Disposes of the gizmo
  91115. */
  91116. PositionGizmo.prototype.dispose = function () {
  91117. this.xGizmo.dispose();
  91118. this.yGizmo.dispose();
  91119. this.zGizmo.dispose();
  91120. };
  91121. /**
  91122. * CustomMeshes are not supported by this gizmo
  91123. * @param mesh The mesh to replace the default mesh of the gizmo
  91124. */
  91125. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  91126. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  91127. };
  91128. return PositionGizmo;
  91129. }(BABYLON.Gizmo));
  91130. BABYLON.PositionGizmo = PositionGizmo;
  91131. })(BABYLON || (BABYLON = {}));
  91132. //# sourceMappingURL=babylon.positionGizmo.js.map
  91133. var BABYLON;
  91134. (function (BABYLON) {
  91135. /**
  91136. * Gizmo that enables rotating a mesh along 3 axis
  91137. */
  91138. var RotationGizmo = /** @class */ (function (_super) {
  91139. __extends(RotationGizmo, _super);
  91140. /**
  91141. * Creates a RotationGizmo
  91142. * @param gizmoLayer The utility layer the gizmo will be added to
  91143. */
  91144. function RotationGizmo(gizmoLayer) {
  91145. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91146. var _this = _super.call(this, gizmoLayer) || this;
  91147. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91148. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91149. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91150. _this.attachedMesh = null;
  91151. return _this;
  91152. }
  91153. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  91154. set: function (mesh) {
  91155. if (this.xGizmo) {
  91156. this.xGizmo.attachedMesh = mesh;
  91157. this.yGizmo.attachedMesh = mesh;
  91158. this.zGizmo.attachedMesh = mesh;
  91159. }
  91160. },
  91161. enumerable: true,
  91162. configurable: true
  91163. });
  91164. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91165. get: function () {
  91166. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91167. },
  91168. set: function (value) {
  91169. if (this.xGizmo) {
  91170. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91171. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91172. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91173. }
  91174. },
  91175. enumerable: true,
  91176. configurable: true
  91177. });
  91178. /**
  91179. * Disposes of the gizmo
  91180. */
  91181. RotationGizmo.prototype.dispose = function () {
  91182. this.xGizmo.dispose();
  91183. this.yGizmo.dispose();
  91184. this.zGizmo.dispose();
  91185. };
  91186. /**
  91187. * CustomMeshes are not supported by this gizmo
  91188. * @param mesh The mesh to replace the default mesh of the gizmo
  91189. */
  91190. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  91191. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  91192. };
  91193. return RotationGizmo;
  91194. }(BABYLON.Gizmo));
  91195. BABYLON.RotationGizmo = RotationGizmo;
  91196. })(BABYLON || (BABYLON = {}));
  91197. //# sourceMappingURL=babylon.rotationGizmo.js.map
  91198. var BABYLON;
  91199. (function (BABYLON) {
  91200. /**
  91201. * Gizmo that enables scaling a mesh along 3 axis
  91202. */
  91203. var ScaleGizmo = /** @class */ (function (_super) {
  91204. __extends(ScaleGizmo, _super);
  91205. /**
  91206. * Creates a ScaleGizmo
  91207. * @param gizmoLayer The utility layer the gizmo will be added to
  91208. */
  91209. function ScaleGizmo(gizmoLayer) {
  91210. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91211. var _this = _super.call(this, gizmoLayer) || this;
  91212. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91213. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91214. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91215. _this.attachedMesh = null;
  91216. return _this;
  91217. }
  91218. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  91219. set: function (mesh) {
  91220. if (this.xGizmo) {
  91221. this.xGizmo.attachedMesh = mesh;
  91222. this.yGizmo.attachedMesh = mesh;
  91223. this.zGizmo.attachedMesh = mesh;
  91224. }
  91225. },
  91226. enumerable: true,
  91227. configurable: true
  91228. });
  91229. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91230. get: function () {
  91231. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91232. },
  91233. set: function (value) {
  91234. if (this.xGizmo) {
  91235. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91236. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91237. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91238. }
  91239. },
  91240. enumerable: true,
  91241. configurable: true
  91242. });
  91243. /**
  91244. * Disposes of the gizmo
  91245. */
  91246. ScaleGizmo.prototype.dispose = function () {
  91247. this.xGizmo.dispose();
  91248. this.yGizmo.dispose();
  91249. this.zGizmo.dispose();
  91250. };
  91251. return ScaleGizmo;
  91252. }(BABYLON.Gizmo));
  91253. BABYLON.ScaleGizmo = ScaleGizmo;
  91254. })(BABYLON || (BABYLON = {}));
  91255. //# sourceMappingURL=babylon.scaleGizmo.js.map
  91256. var BABYLON;
  91257. (function (BABYLON) {
  91258. /**
  91259. * Bounding box gizmo
  91260. */
  91261. var BoundingBoxGizmo = /** @class */ (function (_super) {
  91262. __extends(BoundingBoxGizmo, _super);
  91263. /**
  91264. * Creates an BoundingBoxGizmo
  91265. * @param gizmoLayer The utility layer the gizmo will be added to
  91266. * @param color The color of the gizmo
  91267. */
  91268. function BoundingBoxGizmo(color, gizmoLayer) {
  91269. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91270. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  91271. var _this = _super.call(this, gizmoLayer) || this;
  91272. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  91273. _this._renderObserver = null;
  91274. _this._pointerObserver = null;
  91275. _this._scaleDragSpeed = 0.2;
  91276. _this._tmpQuaternion = new BABYLON.Quaternion();
  91277. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91278. /**
  91279. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  91280. */
  91281. _this.rotationSphereSize = 0.1;
  91282. /**
  91283. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  91284. */
  91285. _this.scaleBoxSize = 0.1;
  91286. /**
  91287. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  91288. */
  91289. _this.fixedDragMeshScreenSize = false;
  91290. /**
  91291. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  91292. */
  91293. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  91294. /**
  91295. * Fired when a rotation sphere or scale box is dragged
  91296. */
  91297. _this.onDragStartObservable = new BABYLON.Observable();
  91298. /**
  91299. * Fired when a rotation sphere or scale box drag is started
  91300. */
  91301. _this.onDragObservable = new BABYLON.Observable();
  91302. /**
  91303. * Fired when a rotation sphere or scale box drag is needed
  91304. */
  91305. _this.onDragEndObservable = new BABYLON.Observable();
  91306. _this._existingMeshScale = new BABYLON.Vector3();
  91307. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  91308. _this._updateScale = false;
  91309. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  91310. // Create Materials
  91311. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91312. coloredMaterial.disableLighting = true;
  91313. coloredMaterial.emissiveColor = color;
  91314. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91315. hoverColoredMaterial.disableLighting = true;
  91316. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  91317. // Build bounding box out of lines
  91318. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91319. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  91320. var lines = [];
  91321. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  91322. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  91323. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91324. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  91325. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91326. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  91327. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91328. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91329. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91330. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91331. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91332. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  91333. lines.forEach(function (l) {
  91334. l.color = color;
  91335. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  91336. l.isPickable = false;
  91337. _this._lineBoundingBox.addChild(l);
  91338. });
  91339. _this._rootMesh.addChild(_this._lineBoundingBox);
  91340. // Create rotation spheres
  91341. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91342. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  91343. var _loop_1 = function (i_1) {
  91344. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  91345. sphere.rotationQuaternion = new BABYLON.Quaternion();
  91346. sphere.material = coloredMaterial;
  91347. // Drag behavior
  91348. _dragBehavior = new BABYLON.PointerDragBehavior({});
  91349. _dragBehavior.moveAttached = false;
  91350. _dragBehavior.updateDragPlane = false;
  91351. sphere.addBehavior(_dragBehavior);
  91352. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  91353. var totalTurnAmountOfDrag = 0;
  91354. _dragBehavior.onDragStartObservable.add(function (event) {
  91355. startingTurnDirection.copyFrom(sphere.forward);
  91356. totalTurnAmountOfDrag = 0;
  91357. });
  91358. _dragBehavior.onDragObservable.add(function (event) {
  91359. _this.onDragObservable.notifyObservers({});
  91360. if (_this.attachedMesh) {
  91361. var worldDragDirection = startingTurnDirection;
  91362. // Project the world right on to the drag plane
  91363. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  91364. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  91365. // project drag delta on to the resulting drag axis and rotate based on that
  91366. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  91367. // Make rotation relative to size of mesh.
  91368. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  91369. // Rotate based on axis
  91370. if (!_this.attachedMesh.rotationQuaternion) {
  91371. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  91372. }
  91373. if (!_this._anchorMesh.rotationQuaternion) {
  91374. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  91375. }
  91376. // Do not allow the object to turn more than a full circle
  91377. totalTurnAmountOfDrag += projectDist;
  91378. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  91379. if (i_1 >= 8) {
  91380. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  91381. }
  91382. else if (i_1 >= 4) {
  91383. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  91384. }
  91385. else {
  91386. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  91387. }
  91388. // Rotate around center of bounding box
  91389. _this._anchorMesh.addChild(_this.attachedMesh);
  91390. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  91391. _this._anchorMesh.removeChild(_this.attachedMesh);
  91392. }
  91393. _this.updateBoundingBox();
  91394. }
  91395. });
  91396. // Selection/deselection
  91397. _dragBehavior.onDragStartObservable.add(function () {
  91398. _this.onDragStartObservable.notifyObservers({});
  91399. _this._selectNode(sphere);
  91400. });
  91401. _dragBehavior.onDragEndObservable.add(function () {
  91402. _this.onDragEndObservable.notifyObservers({});
  91403. _this._selectNode(null);
  91404. });
  91405. this_1._rotateSpheresParent.addChild(sphere);
  91406. };
  91407. var this_1 = this, _dragBehavior;
  91408. for (var i_1 = 0; i_1 < 12; i_1++) {
  91409. _loop_1(i_1);
  91410. }
  91411. _this._rootMesh.addChild(_this._rotateSpheresParent);
  91412. // Create scale cubes
  91413. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91414. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  91415. for (var i = 0; i < 2; i++) {
  91416. for (var j = 0; j < 2; j++) {
  91417. var _loop_2 = function () {
  91418. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  91419. box.material = coloredMaterial;
  91420. // Dragging logic
  91421. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  91422. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91423. _dragBehavior.moveAttached = false;
  91424. box.addBehavior(_dragBehavior);
  91425. _dragBehavior.onDragObservable.add(function (event) {
  91426. _this.onDragObservable.notifyObservers({});
  91427. if (_this.attachedMesh) {
  91428. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  91429. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  91430. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  91431. _this.updateBoundingBox();
  91432. // Scale from the position of the opposite corner
  91433. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  91434. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  91435. _this._anchorMesh.addChild(_this.attachedMesh);
  91436. _this._anchorMesh.scaling.addInPlace(deltaScale);
  91437. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  91438. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  91439. }
  91440. _this._anchorMesh.removeChild(_this.attachedMesh);
  91441. }
  91442. });
  91443. // Selection/deselection
  91444. _dragBehavior.onDragStartObservable.add(function () {
  91445. _this.onDragStartObservable.notifyObservers({});
  91446. _this._selectNode(box);
  91447. });
  91448. _dragBehavior.onDragEndObservable.add(function () {
  91449. _this.onDragEndObservable.notifyObservers({});
  91450. _this._selectNode(null);
  91451. });
  91452. this_2._scaleBoxesParent.addChild(box);
  91453. };
  91454. var this_2 = this, _dragBehavior;
  91455. for (var k = 0; k < 2; k++) {
  91456. _loop_2();
  91457. }
  91458. }
  91459. }
  91460. _this._rootMesh.addChild(_this._scaleBoxesParent);
  91461. // Hover color change
  91462. var pointerIds = new Array();
  91463. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91464. if (!pointerIds[pointerInfo.event.pointerId]) {
  91465. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  91466. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  91467. pointerIds[pointerInfo.event.pointerId] = mesh;
  91468. mesh.material = hoverColoredMaterial;
  91469. }
  91470. });
  91471. }
  91472. else {
  91473. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  91474. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  91475. delete pointerIds[pointerInfo.event.pointerId];
  91476. }
  91477. }
  91478. });
  91479. // Update bounding box positions
  91480. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  91481. // Only update the bouding box if scaling has changed
  91482. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  91483. _this.updateBoundingBox();
  91484. }
  91485. });
  91486. _this.updateBoundingBox();
  91487. return _this;
  91488. }
  91489. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  91490. if (value) {
  91491. // Reset anchor mesh to match attached mesh's scale
  91492. // This is needed to avoid invalid box/sphere position on first drag
  91493. this._anchorMesh.addChild(value);
  91494. this._anchorMesh.removeChild(value);
  91495. this.updateBoundingBox();
  91496. }
  91497. };
  91498. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  91499. this._rotateSpheresParent.getChildMeshes()
  91500. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  91501. m.isVisible = (!selectedMesh || m == selectedMesh);
  91502. });
  91503. };
  91504. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  91505. var _this = this;
  91506. mesh.computeWorldMatrix(true);
  91507. mesh.getChildMeshes().forEach(function (m) {
  91508. _this._recurseComputeWorld(m);
  91509. });
  91510. };
  91511. /**
  91512. * Updates the bounding box information for the Gizmo
  91513. */
  91514. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  91515. this._update();
  91516. if (this.attachedMesh) {
  91517. // Rotate based on axis
  91518. if (!this.attachedMesh.rotationQuaternion) {
  91519. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  91520. }
  91521. if (!this._anchorMesh.rotationQuaternion) {
  91522. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  91523. }
  91524. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  91525. // Store original position and reset mesh to origin before computing the bounding box
  91526. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  91527. this._tmpVector.copyFrom(this.attachedMesh.position);
  91528. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  91529. this.attachedMesh.position.set(0, 0, 0);
  91530. // Update bounding dimensions/positions
  91531. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  91532. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  91533. // Update gizmo to match bounding box scaling and rotation
  91534. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  91535. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91536. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  91537. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  91538. this._lineBoundingBox.computeWorldMatrix();
  91539. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  91540. // restore position/rotation values
  91541. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  91542. this.attachedMesh.position.copyFrom(this._tmpVector);
  91543. this._recurseComputeWorld(this.attachedMesh);
  91544. }
  91545. // Update rotation sphere locations
  91546. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  91547. for (var i = 0; i < 3; i++) {
  91548. for (var j = 0; j < 2; j++) {
  91549. for (var k = 0; k < 2; k++) {
  91550. var index = ((i * 4) + (j * 2)) + k;
  91551. if (i == 0) {
  91552. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91553. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91554. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91555. }
  91556. if (i == 1) {
  91557. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  91558. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91559. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91560. }
  91561. if (i == 2) {
  91562. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  91563. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91564. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91565. }
  91566. if (this.fixedDragMeshScreenSize) {
  91567. this._rootMesh.computeWorldMatrix();
  91568. this._rotateSpheresParent.computeWorldMatrix();
  91569. rotateSpheres[index].computeWorldMatrix();
  91570. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91571. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91572. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91573. }
  91574. else {
  91575. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  91576. }
  91577. }
  91578. }
  91579. }
  91580. // Update scale box locations
  91581. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  91582. for (var i = 0; i < 2; i++) {
  91583. for (var j = 0; j < 2; j++) {
  91584. for (var k = 0; k < 2; k++) {
  91585. var index = ((i * 4) + (j * 2)) + k;
  91586. if (scaleBoxes[index]) {
  91587. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91588. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91589. if (this.fixedDragMeshScreenSize) {
  91590. this._rootMesh.computeWorldMatrix();
  91591. this._scaleBoxesParent.computeWorldMatrix();
  91592. scaleBoxes[index].computeWorldMatrix();
  91593. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91594. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91595. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91596. }
  91597. else {
  91598. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  91599. }
  91600. }
  91601. }
  91602. }
  91603. }
  91604. if (this.attachedMesh) {
  91605. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  91606. }
  91607. };
  91608. /**
  91609. * Enables rotation on the specified axis and disables rotation on the others
  91610. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  91611. */
  91612. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  91613. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  91614. if (i < 4) {
  91615. m.setEnabled(axis.indexOf("x") != -1);
  91616. }
  91617. else if (i < 8) {
  91618. m.setEnabled(axis.indexOf("y") != -1);
  91619. }
  91620. else {
  91621. m.setEnabled(axis.indexOf("z") != -1);
  91622. }
  91623. });
  91624. };
  91625. /**
  91626. * Disposes of the gizmo
  91627. */
  91628. BoundingBoxGizmo.prototype.dispose = function () {
  91629. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91630. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  91631. this._lineBoundingBox.dispose();
  91632. this._rotateSpheresParent.dispose();
  91633. this._scaleBoxesParent.dispose();
  91634. _super.prototype.dispose.call(this);
  91635. };
  91636. /**
  91637. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  91638. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  91639. * @returns the bounding box mesh with the passed in mesh as a child
  91640. */
  91641. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  91642. var makeNotPickable = function (root) {
  91643. root.isPickable = false;
  91644. root.getChildMeshes().forEach(function (c) {
  91645. makeNotPickable(c);
  91646. });
  91647. };
  91648. makeNotPickable(mesh);
  91649. // Reset position to get boudning box from origin with no rotation
  91650. if (!mesh.rotationQuaternion) {
  91651. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  91652. }
  91653. var oldPos = mesh.position.clone();
  91654. var oldRot = mesh.rotationQuaternion.clone();
  91655. mesh.rotationQuaternion.set(0, 0, 0, 1);
  91656. mesh.position.set(0, 0, 0);
  91657. // Update bounding dimensions/positions
  91658. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  91659. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  91660. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  91661. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91662. // Restore original positions
  91663. mesh.addChild(box);
  91664. mesh.rotationQuaternion.copyFrom(oldRot);
  91665. mesh.position.copyFrom(oldPos);
  91666. // Reverse parenting
  91667. mesh.removeChild(box);
  91668. box.addChild(mesh);
  91669. box.visibility = 0;
  91670. return box;
  91671. };
  91672. /**
  91673. * CustomMeshes are not supported by this gizmo
  91674. * @param mesh The mesh to replace the default mesh of the gizmo
  91675. */
  91676. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  91677. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  91678. };
  91679. return BoundingBoxGizmo;
  91680. }(BABYLON.Gizmo));
  91681. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  91682. })(BABYLON || (BABYLON = {}));
  91683. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  91684. var BABYLON;
  91685. (function (BABYLON) {
  91686. /**
  91687. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  91688. */
  91689. var GizmoManager = /** @class */ (function () {
  91690. /**
  91691. * Instatiates a gizmo manager
  91692. * @param scene the scene to overlay the gizmos on top of
  91693. */
  91694. function GizmoManager(scene) {
  91695. var _this = this;
  91696. this.scene = scene;
  91697. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  91698. this._pointerObserver = null;
  91699. this._attachedMesh = null;
  91700. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  91701. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  91702. /**
  91703. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  91704. */
  91705. this.attachableMeshes = null;
  91706. /**
  91707. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  91708. */
  91709. this.usePointerToAttachGizmos = true;
  91710. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  91711. // Instatiate/dispose gizmos based on pointer actions
  91712. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  91713. if (!_this.usePointerToAttachGizmos) {
  91714. return;
  91715. }
  91716. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91717. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  91718. var node = pointerInfo.pickInfo.pickedMesh;
  91719. if (_this.attachableMeshes == null) {
  91720. // Attach to the most parent node
  91721. while (node && node.parent != null) {
  91722. node = node.parent;
  91723. }
  91724. }
  91725. else {
  91726. // Attach to the parent node that is an attachableMesh
  91727. var found = false;
  91728. _this.attachableMeshes.forEach(function (mesh) {
  91729. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  91730. node = mesh;
  91731. found = true;
  91732. }
  91733. });
  91734. if (!found) {
  91735. node = null;
  91736. }
  91737. }
  91738. if (node instanceof BABYLON.AbstractMesh) {
  91739. _this.attachToMesh(node);
  91740. }
  91741. }
  91742. else {
  91743. _this.attachToMesh(null);
  91744. }
  91745. }
  91746. });
  91747. }
  91748. /**
  91749. * Attaches a set of gizmos to the specified mesh
  91750. * @param mesh The mesh the gizmo's should be attached to
  91751. */
  91752. GizmoManager.prototype.attachToMesh = function (mesh) {
  91753. if (this._attachedMesh) {
  91754. this._attachedMesh.removeBehavior(this._dragBehavior);
  91755. }
  91756. this._attachedMesh = mesh;
  91757. for (var key in this.gizmos) {
  91758. var gizmo = (this.gizmos[key]);
  91759. if (gizmo && this._gizmosEnabled[key]) {
  91760. gizmo.attachedMesh = mesh;
  91761. }
  91762. }
  91763. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  91764. this._attachedMesh.addBehavior(this._dragBehavior);
  91765. }
  91766. };
  91767. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  91768. get: function () {
  91769. return this._gizmosEnabled.positionGizmo;
  91770. },
  91771. /**
  91772. * If the position gizmo is enabled
  91773. */
  91774. set: function (value) {
  91775. if (value) {
  91776. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  91777. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91778. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  91779. }
  91780. else if (this.gizmos.positionGizmo) {
  91781. this.gizmos.positionGizmo.attachedMesh = null;
  91782. }
  91783. this._gizmosEnabled.positionGizmo = value;
  91784. },
  91785. enumerable: true,
  91786. configurable: true
  91787. });
  91788. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  91789. get: function () {
  91790. return this._gizmosEnabled.rotationGizmo;
  91791. },
  91792. /**
  91793. * If the rotation gizmo is enabled
  91794. */
  91795. set: function (value) {
  91796. if (value) {
  91797. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  91798. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91799. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  91800. }
  91801. else if (this.gizmos.rotationGizmo) {
  91802. this.gizmos.rotationGizmo.attachedMesh = null;
  91803. }
  91804. this._gizmosEnabled.rotationGizmo = value;
  91805. },
  91806. enumerable: true,
  91807. configurable: true
  91808. });
  91809. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  91810. get: function () {
  91811. return this._gizmosEnabled.scaleGizmo;
  91812. },
  91813. /**
  91814. * If the scale gizmo is enabled
  91815. */
  91816. set: function (value) {
  91817. if (value) {
  91818. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  91819. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  91820. }
  91821. else if (this.gizmos.scaleGizmo) {
  91822. this.gizmos.scaleGizmo.attachedMesh = null;
  91823. }
  91824. this._gizmosEnabled.scaleGizmo = value;
  91825. },
  91826. enumerable: true,
  91827. configurable: true
  91828. });
  91829. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  91830. get: function () {
  91831. return this._gizmosEnabled.boundingBoxGizmo;
  91832. },
  91833. /**
  91834. * If the boundingBox gizmo is enabled
  91835. */
  91836. set: function (value) {
  91837. if (value) {
  91838. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  91839. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  91840. if (this._attachedMesh) {
  91841. this._attachedMesh.removeBehavior(this._dragBehavior);
  91842. this._attachedMesh.addBehavior(this._dragBehavior);
  91843. }
  91844. }
  91845. else if (this.gizmos.boundingBoxGizmo) {
  91846. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  91847. }
  91848. this._gizmosEnabled.boundingBoxGizmo = value;
  91849. },
  91850. enumerable: true,
  91851. configurable: true
  91852. });
  91853. /**
  91854. * Disposes of the gizmo manager
  91855. */
  91856. GizmoManager.prototype.dispose = function () {
  91857. this.scene.onPointerObservable.remove(this._pointerObserver);
  91858. for (var key in this.gizmos) {
  91859. var gizmo = (this.gizmos[key]);
  91860. if (gizmo) {
  91861. gizmo.dispose();
  91862. }
  91863. }
  91864. this._dragBehavior.detach();
  91865. this._gizmoLayer.dispose();
  91866. };
  91867. return GizmoManager;
  91868. }());
  91869. BABYLON.GizmoManager = GizmoManager;
  91870. })(BABYLON || (BABYLON = {}));
  91871. //# sourceMappingURL=babylon.gizmoManager.js.map
  91872. var BABYLON;
  91873. (function (BABYLON) {
  91874. /**
  91875. * Defines a target to use with MorphTargetManager
  91876. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91877. */
  91878. var MorphTarget = /** @class */ (function () {
  91879. /**
  91880. * Creates a new MorphTarget
  91881. * @param name defines the name of the target
  91882. * @param influence defines the influence to use
  91883. */
  91884. function MorphTarget(
  91885. /** defines the name of the target */
  91886. name, influence, scene) {
  91887. if (influence === void 0) { influence = 0; }
  91888. if (scene === void 0) { scene = null; }
  91889. this.name = name;
  91890. /**
  91891. * Gets or sets the list of animations
  91892. */
  91893. this.animations = new Array();
  91894. this._positions = null;
  91895. this._normals = null;
  91896. this._tangents = null;
  91897. /**
  91898. * Observable raised when the influence changes
  91899. */
  91900. this.onInfluenceChanged = new BABYLON.Observable();
  91901. this._animationPropertiesOverride = null;
  91902. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91903. this.influence = influence;
  91904. }
  91905. Object.defineProperty(MorphTarget.prototype, "influence", {
  91906. /**
  91907. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  91908. */
  91909. get: function () {
  91910. return this._influence;
  91911. },
  91912. set: function (influence) {
  91913. if (this._influence === influence) {
  91914. return;
  91915. }
  91916. var previous = this._influence;
  91917. this._influence = influence;
  91918. if (this.onInfluenceChanged.hasObservers) {
  91919. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  91920. }
  91921. },
  91922. enumerable: true,
  91923. configurable: true
  91924. });
  91925. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  91926. /**
  91927. * Gets or sets the animation properties override
  91928. */
  91929. get: function () {
  91930. if (!this._animationPropertiesOverride && this._scene) {
  91931. return this._scene.animationPropertiesOverride;
  91932. }
  91933. return this._animationPropertiesOverride;
  91934. },
  91935. set: function (value) {
  91936. this._animationPropertiesOverride = value;
  91937. },
  91938. enumerable: true,
  91939. configurable: true
  91940. });
  91941. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  91942. /**
  91943. * Gets a boolean defining if the target contains position data
  91944. */
  91945. get: function () {
  91946. return !!this._positions;
  91947. },
  91948. enumerable: true,
  91949. configurable: true
  91950. });
  91951. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  91952. /**
  91953. * Gets a boolean defining if the target contains normal data
  91954. */
  91955. get: function () {
  91956. return !!this._normals;
  91957. },
  91958. enumerable: true,
  91959. configurable: true
  91960. });
  91961. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  91962. /**
  91963. * Gets a boolean defining if the target contains tangent data
  91964. */
  91965. get: function () {
  91966. return !!this._tangents;
  91967. },
  91968. enumerable: true,
  91969. configurable: true
  91970. });
  91971. /**
  91972. * Affects position data to this target
  91973. * @param data defines the position data to use
  91974. */
  91975. MorphTarget.prototype.setPositions = function (data) {
  91976. this._positions = data;
  91977. };
  91978. /**
  91979. * Gets the position data stored in this target
  91980. * @returns a FloatArray containing the position data (or null if not present)
  91981. */
  91982. MorphTarget.prototype.getPositions = function () {
  91983. return this._positions;
  91984. };
  91985. /**
  91986. * Affects normal data to this target
  91987. * @param data defines the normal data to use
  91988. */
  91989. MorphTarget.prototype.setNormals = function (data) {
  91990. this._normals = data;
  91991. };
  91992. /**
  91993. * Gets the normal data stored in this target
  91994. * @returns a FloatArray containing the normal data (or null if not present)
  91995. */
  91996. MorphTarget.prototype.getNormals = function () {
  91997. return this._normals;
  91998. };
  91999. /**
  92000. * Affects tangent data to this target
  92001. * @param data defines the tangent data to use
  92002. */
  92003. MorphTarget.prototype.setTangents = function (data) {
  92004. this._tangents = data;
  92005. };
  92006. /**
  92007. * Gets the tangent data stored in this target
  92008. * @returns a FloatArray containing the tangent data (or null if not present)
  92009. */
  92010. MorphTarget.prototype.getTangents = function () {
  92011. return this._tangents;
  92012. };
  92013. /**
  92014. * Serializes the current target into a Serialization object
  92015. * @returns the serialized object
  92016. */
  92017. MorphTarget.prototype.serialize = function () {
  92018. var serializationObject = {};
  92019. serializationObject.name = this.name;
  92020. serializationObject.influence = this.influence;
  92021. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  92022. if (this.hasNormals) {
  92023. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  92024. }
  92025. if (this.hasTangents) {
  92026. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  92027. }
  92028. // Animations
  92029. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  92030. return serializationObject;
  92031. };
  92032. // Statics
  92033. /**
  92034. * Creates a new target from serialized data
  92035. * @param serializationObject defines the serialized data to use
  92036. * @returns a new MorphTarget
  92037. */
  92038. MorphTarget.Parse = function (serializationObject) {
  92039. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  92040. result.setPositions(serializationObject.positions);
  92041. if (serializationObject.normals) {
  92042. result.setNormals(serializationObject.normals);
  92043. }
  92044. if (serializationObject.tangents) {
  92045. result.setTangents(serializationObject.tangents);
  92046. }
  92047. // Animations
  92048. if (serializationObject.animations) {
  92049. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  92050. var parsedAnimation = serializationObject.animations[animationIndex];
  92051. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  92052. }
  92053. }
  92054. return result;
  92055. };
  92056. /**
  92057. * Creates a MorphTarget from mesh data
  92058. * @param mesh defines the source mesh
  92059. * @param name defines the name to use for the new target
  92060. * @param influence defines the influence to attach to the target
  92061. * @returns a new MorphTarget
  92062. */
  92063. MorphTarget.FromMesh = function (mesh, name, influence) {
  92064. if (!name) {
  92065. name = mesh.name;
  92066. }
  92067. var result = new MorphTarget(name, influence, mesh.getScene());
  92068. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  92069. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  92070. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  92071. }
  92072. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  92073. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  92074. }
  92075. return result;
  92076. };
  92077. return MorphTarget;
  92078. }());
  92079. BABYLON.MorphTarget = MorphTarget;
  92080. })(BABYLON || (BABYLON = {}));
  92081. //# sourceMappingURL=babylon.morphTarget.js.map
  92082. var BABYLON;
  92083. (function (BABYLON) {
  92084. /**
  92085. * This class is used to deform meshes using morphing between different targets
  92086. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  92087. */
  92088. var MorphTargetManager = /** @class */ (function () {
  92089. /**
  92090. * Creates a new MorphTargetManager
  92091. * @param scene defines the current scene
  92092. */
  92093. function MorphTargetManager(scene) {
  92094. if (scene === void 0) { scene = null; }
  92095. this._targets = new Array();
  92096. this._targetObservable = new Array();
  92097. this._activeTargets = new BABYLON.SmartArray(16);
  92098. this._supportsNormals = false;
  92099. this._supportsTangents = false;
  92100. this._vertexCount = 0;
  92101. this._uniqueId = 0;
  92102. this._tempInfluences = new Array();
  92103. if (!scene) {
  92104. scene = BABYLON.Engine.LastCreatedScene;
  92105. }
  92106. this._scene = scene;
  92107. if (this._scene) {
  92108. this._scene.morphTargetManagers.push(this);
  92109. this._uniqueId = this._scene.getUniqueId();
  92110. }
  92111. }
  92112. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  92113. /**
  92114. * Gets the unique ID of this manager
  92115. */
  92116. get: function () {
  92117. return this._uniqueId;
  92118. },
  92119. enumerable: true,
  92120. configurable: true
  92121. });
  92122. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  92123. /**
  92124. * Gets the number of vertices handled by this manager
  92125. */
  92126. get: function () {
  92127. return this._vertexCount;
  92128. },
  92129. enumerable: true,
  92130. configurable: true
  92131. });
  92132. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  92133. /**
  92134. * Gets a boolean indicating if this manager supports morphing of normals
  92135. */
  92136. get: function () {
  92137. return this._supportsNormals;
  92138. },
  92139. enumerable: true,
  92140. configurable: true
  92141. });
  92142. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  92143. /**
  92144. * Gets a boolean indicating if this manager supports morphing of tangents
  92145. */
  92146. get: function () {
  92147. return this._supportsTangents;
  92148. },
  92149. enumerable: true,
  92150. configurable: true
  92151. });
  92152. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  92153. /**
  92154. * Gets the number of targets stored in this manager
  92155. */
  92156. get: function () {
  92157. return this._targets.length;
  92158. },
  92159. enumerable: true,
  92160. configurable: true
  92161. });
  92162. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  92163. /**
  92164. * Gets the number of influencers (ie. the number of targets with influences > 0)
  92165. */
  92166. get: function () {
  92167. return this._activeTargets.length;
  92168. },
  92169. enumerable: true,
  92170. configurable: true
  92171. });
  92172. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  92173. /**
  92174. * Gets the list of influences (one per target)
  92175. */
  92176. get: function () {
  92177. return this._influences;
  92178. },
  92179. enumerable: true,
  92180. configurable: true
  92181. });
  92182. /**
  92183. * Gets the active target at specified index. An active target is a target with an influence > 0
  92184. * @param index defines the index to check
  92185. * @returns the requested target
  92186. */
  92187. MorphTargetManager.prototype.getActiveTarget = function (index) {
  92188. return this._activeTargets.data[index];
  92189. };
  92190. /**
  92191. * Gets the target at specified index
  92192. * @param index defines the index to check
  92193. * @returns the requested target
  92194. */
  92195. MorphTargetManager.prototype.getTarget = function (index) {
  92196. return this._targets[index];
  92197. };
  92198. /**
  92199. * Add a new target to this manager
  92200. * @param target defines the target to add
  92201. */
  92202. MorphTargetManager.prototype.addTarget = function (target) {
  92203. var _this = this;
  92204. this._targets.push(target);
  92205. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  92206. _this._syncActiveTargets(needUpdate);
  92207. }));
  92208. this._syncActiveTargets(true);
  92209. };
  92210. /**
  92211. * Removes a target from the manager
  92212. * @param target defines the target to remove
  92213. */
  92214. MorphTargetManager.prototype.removeTarget = function (target) {
  92215. var index = this._targets.indexOf(target);
  92216. if (index >= 0) {
  92217. this._targets.splice(index, 1);
  92218. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  92219. this._syncActiveTargets(true);
  92220. }
  92221. };
  92222. /**
  92223. * Serializes the current manager into a Serialization object
  92224. * @returns the serialized object
  92225. */
  92226. MorphTargetManager.prototype.serialize = function () {
  92227. var serializationObject = {};
  92228. serializationObject.id = this.uniqueId;
  92229. serializationObject.targets = [];
  92230. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  92231. var target = _a[_i];
  92232. serializationObject.targets.push(target.serialize());
  92233. }
  92234. return serializationObject;
  92235. };
  92236. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  92237. var influenceCount = 0;
  92238. this._activeTargets.reset();
  92239. this._supportsNormals = true;
  92240. this._supportsTangents = true;
  92241. this._vertexCount = 0;
  92242. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  92243. var target = _a[_i];
  92244. this._activeTargets.push(target);
  92245. this._tempInfluences[influenceCount++] = target.influence;
  92246. var positions = target.getPositions();
  92247. if (positions) {
  92248. this._supportsNormals = this._supportsNormals && target.hasNormals;
  92249. this._supportsTangents = this._supportsTangents && target.hasTangents;
  92250. var vertexCount = positions.length / 3;
  92251. if (this._vertexCount === 0) {
  92252. this._vertexCount = vertexCount;
  92253. }
  92254. else if (this._vertexCount !== vertexCount) {
  92255. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  92256. return;
  92257. }
  92258. }
  92259. }
  92260. if (!this._influences || this._influences.length !== influenceCount) {
  92261. this._influences = new Float32Array(influenceCount);
  92262. }
  92263. for (var index = 0; index < influenceCount; index++) {
  92264. this._influences[index] = this._tempInfluences[index];
  92265. }
  92266. if (needUpdate) {
  92267. this.synchronize();
  92268. }
  92269. };
  92270. /**
  92271. * Syncrhonize the targets with all the meshes using this morph target manager
  92272. */
  92273. MorphTargetManager.prototype.synchronize = function () {
  92274. if (!this._scene) {
  92275. return;
  92276. }
  92277. // Flag meshes as dirty to resync with the active targets
  92278. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  92279. var mesh = _a[_i];
  92280. if (mesh.morphTargetManager === this) {
  92281. mesh._syncGeometryWithMorphTargetManager();
  92282. }
  92283. }
  92284. };
  92285. // Statics
  92286. /**
  92287. * Creates a new MorphTargetManager from serialized data
  92288. * @param serializationObject defines the serialized data
  92289. * @param scene defines the hosting scene
  92290. * @returns the new MorphTargetManager
  92291. */
  92292. MorphTargetManager.Parse = function (serializationObject, scene) {
  92293. var result = new MorphTargetManager(scene);
  92294. result._uniqueId = serializationObject.id;
  92295. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  92296. var targetData = _a[_i];
  92297. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  92298. }
  92299. return result;
  92300. };
  92301. return MorphTargetManager;
  92302. }());
  92303. BABYLON.MorphTargetManager = MorphTargetManager;
  92304. })(BABYLON || (BABYLON = {}));
  92305. //# sourceMappingURL=babylon.morphTargetManager.js.map
  92306. var BABYLON;
  92307. (function (BABYLON) {
  92308. var Octree = /** @class */ (function () {
  92309. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  92310. if (maxDepth === void 0) { maxDepth = 2; }
  92311. this.maxDepth = maxDepth;
  92312. this.dynamicContent = new Array();
  92313. this._maxBlockCapacity = maxBlockCapacity || 64;
  92314. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  92315. this._creationFunc = creationFunc;
  92316. }
  92317. // Methods
  92318. Octree.prototype.update = function (worldMin, worldMax, entries) {
  92319. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  92320. };
  92321. Octree.prototype.addMesh = function (entry) {
  92322. for (var index = 0; index < this.blocks.length; index++) {
  92323. var block = this.blocks[index];
  92324. block.addEntry(entry);
  92325. }
  92326. };
  92327. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  92328. this._selectionContent.reset();
  92329. for (var index = 0; index < this.blocks.length; index++) {
  92330. var block = this.blocks[index];
  92331. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  92332. }
  92333. if (allowDuplicate) {
  92334. this._selectionContent.concat(this.dynamicContent);
  92335. }
  92336. else {
  92337. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92338. }
  92339. return this._selectionContent;
  92340. };
  92341. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  92342. this._selectionContent.reset();
  92343. for (var index = 0; index < this.blocks.length; index++) {
  92344. var block = this.blocks[index];
  92345. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  92346. }
  92347. if (allowDuplicate) {
  92348. this._selectionContent.concat(this.dynamicContent);
  92349. }
  92350. else {
  92351. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92352. }
  92353. return this._selectionContent;
  92354. };
  92355. Octree.prototype.intersectsRay = function (ray) {
  92356. this._selectionContent.reset();
  92357. for (var index = 0; index < this.blocks.length; index++) {
  92358. var block = this.blocks[index];
  92359. block.intersectsRay(ray, this._selectionContent);
  92360. }
  92361. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92362. return this._selectionContent;
  92363. };
  92364. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  92365. target.blocks = new Array();
  92366. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  92367. // Segmenting space
  92368. for (var x = 0; x < 2; x++) {
  92369. for (var y = 0; y < 2; y++) {
  92370. for (var z = 0; z < 2; z++) {
  92371. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  92372. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  92373. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  92374. block.addEntries(entries);
  92375. target.blocks.push(block);
  92376. }
  92377. }
  92378. }
  92379. };
  92380. Octree.CreationFuncForMeshes = function (entry, block) {
  92381. var boundingInfo = entry.getBoundingInfo();
  92382. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  92383. block.entries.push(entry);
  92384. }
  92385. };
  92386. Octree.CreationFuncForSubMeshes = function (entry, block) {
  92387. var boundingInfo = entry.getBoundingInfo();
  92388. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  92389. block.entries.push(entry);
  92390. }
  92391. };
  92392. return Octree;
  92393. }());
  92394. BABYLON.Octree = Octree;
  92395. })(BABYLON || (BABYLON = {}));
  92396. //# sourceMappingURL=babylon.octree.js.map
  92397. var BABYLON;
  92398. (function (BABYLON) {
  92399. var OctreeBlock = /** @class */ (function () {
  92400. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  92401. this.entries = new Array();
  92402. this._boundingVectors = new Array();
  92403. this._capacity = capacity;
  92404. this._depth = depth;
  92405. this._maxDepth = maxDepth;
  92406. this._creationFunc = creationFunc;
  92407. this._minPoint = minPoint;
  92408. this._maxPoint = maxPoint;
  92409. this._boundingVectors.push(minPoint.clone());
  92410. this._boundingVectors.push(maxPoint.clone());
  92411. this._boundingVectors.push(minPoint.clone());
  92412. this._boundingVectors[2].x = maxPoint.x;
  92413. this._boundingVectors.push(minPoint.clone());
  92414. this._boundingVectors[3].y = maxPoint.y;
  92415. this._boundingVectors.push(minPoint.clone());
  92416. this._boundingVectors[4].z = maxPoint.z;
  92417. this._boundingVectors.push(maxPoint.clone());
  92418. this._boundingVectors[5].z = minPoint.z;
  92419. this._boundingVectors.push(maxPoint.clone());
  92420. this._boundingVectors[6].x = minPoint.x;
  92421. this._boundingVectors.push(maxPoint.clone());
  92422. this._boundingVectors[7].y = minPoint.y;
  92423. }
  92424. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  92425. // Property
  92426. get: function () {
  92427. return this._capacity;
  92428. },
  92429. enumerable: true,
  92430. configurable: true
  92431. });
  92432. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  92433. get: function () {
  92434. return this._minPoint;
  92435. },
  92436. enumerable: true,
  92437. configurable: true
  92438. });
  92439. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  92440. get: function () {
  92441. return this._maxPoint;
  92442. },
  92443. enumerable: true,
  92444. configurable: true
  92445. });
  92446. // Methods
  92447. OctreeBlock.prototype.addEntry = function (entry) {
  92448. if (this.blocks) {
  92449. for (var index = 0; index < this.blocks.length; index++) {
  92450. var block = this.blocks[index];
  92451. block.addEntry(entry);
  92452. }
  92453. return;
  92454. }
  92455. this._creationFunc(entry, this);
  92456. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  92457. this.createInnerBlocks();
  92458. }
  92459. };
  92460. OctreeBlock.prototype.addEntries = function (entries) {
  92461. for (var index = 0; index < entries.length; index++) {
  92462. var mesh = entries[index];
  92463. this.addEntry(mesh);
  92464. }
  92465. };
  92466. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  92467. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  92468. if (this.blocks) {
  92469. for (var index = 0; index < this.blocks.length; index++) {
  92470. var block = this.blocks[index];
  92471. block.select(frustumPlanes, selection, allowDuplicate);
  92472. }
  92473. return;
  92474. }
  92475. if (allowDuplicate) {
  92476. selection.concat(this.entries);
  92477. }
  92478. else {
  92479. selection.concatWithNoDuplicate(this.entries);
  92480. }
  92481. }
  92482. };
  92483. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  92484. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  92485. if (this.blocks) {
  92486. for (var index = 0; index < this.blocks.length; index++) {
  92487. var block = this.blocks[index];
  92488. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  92489. }
  92490. return;
  92491. }
  92492. if (allowDuplicate) {
  92493. selection.concat(this.entries);
  92494. }
  92495. else {
  92496. selection.concatWithNoDuplicate(this.entries);
  92497. }
  92498. }
  92499. };
  92500. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  92501. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  92502. if (this.blocks) {
  92503. for (var index = 0; index < this.blocks.length; index++) {
  92504. var block = this.blocks[index];
  92505. block.intersectsRay(ray, selection);
  92506. }
  92507. return;
  92508. }
  92509. selection.concatWithNoDuplicate(this.entries);
  92510. }
  92511. };
  92512. OctreeBlock.prototype.createInnerBlocks = function () {
  92513. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  92514. };
  92515. return OctreeBlock;
  92516. }());
  92517. BABYLON.OctreeBlock = OctreeBlock;
  92518. })(BABYLON || (BABYLON = {}));
  92519. //# sourceMappingURL=babylon.octreeBlock.js.map
  92520. var BABYLON;
  92521. (function (BABYLON) {
  92522. /**
  92523. * Postprocess used to generate anaglyphic rendering
  92524. */
  92525. var AnaglyphPostProcess = /** @class */ (function (_super) {
  92526. __extends(AnaglyphPostProcess, _super);
  92527. /**
  92528. * Creates a new AnaglyphPostProcess
  92529. * @param name defines postprocess name
  92530. * @param options defines creation options or target ratio scale
  92531. * @param rigCameras defines cameras using this postprocess
  92532. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  92533. * @param engine defines hosting engine
  92534. * @param reusable defines if the postprocess will be reused multiple times per frame
  92535. */
  92536. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  92537. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  92538. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92539. _this.onApplyObservable.add(function (effect) {
  92540. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  92541. });
  92542. return _this;
  92543. }
  92544. return AnaglyphPostProcess;
  92545. }(BABYLON.PostProcess));
  92546. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  92547. })(BABYLON || (BABYLON = {}));
  92548. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  92549. var BABYLON;
  92550. (function (BABYLON) {
  92551. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  92552. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92553. });
  92554. /**
  92555. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  92556. */
  92557. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  92558. __extends(AnaglyphArcRotateCamera, _super);
  92559. /**
  92560. * Creates a new AnaglyphArcRotateCamera
  92561. * @param name defines camera name
  92562. * @param alpha defines alpha angle (in radians)
  92563. * @param beta defines beta angle (in radians)
  92564. * @param radius defines radius
  92565. * @param target defines camera target
  92566. * @param interaxialDistance defines distance between each color axis
  92567. * @param scene defines the hosting scene
  92568. */
  92569. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  92570. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92571. _this.interaxialDistance = interaxialDistance;
  92572. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92573. return _this;
  92574. }
  92575. /**
  92576. * Gets camera class name
  92577. * @returns AnaglyphArcRotateCamera
  92578. */
  92579. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  92580. return "AnaglyphArcRotateCamera";
  92581. };
  92582. return AnaglyphArcRotateCamera;
  92583. }(BABYLON.ArcRotateCamera));
  92584. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  92585. })(BABYLON || (BABYLON = {}));
  92586. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  92587. var BABYLON;
  92588. (function (BABYLON) {
  92589. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  92590. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92591. });
  92592. /**
  92593. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  92594. */
  92595. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  92596. __extends(AnaglyphFreeCamera, _super);
  92597. /**
  92598. * Creates a new AnaglyphFreeCamera
  92599. * @param name defines camera name
  92600. * @param position defines initial position
  92601. * @param interaxialDistance defines distance between each color axis
  92602. * @param scene defines the hosting scene
  92603. */
  92604. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  92605. var _this = _super.call(this, name, position, scene) || this;
  92606. _this.interaxialDistance = interaxialDistance;
  92607. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92608. return _this;
  92609. }
  92610. /**
  92611. * Gets camera class name
  92612. * @returns AnaglyphFreeCamera
  92613. */
  92614. AnaglyphFreeCamera.prototype.getClassName = function () {
  92615. return "AnaglyphFreeCamera";
  92616. };
  92617. return AnaglyphFreeCamera;
  92618. }(BABYLON.FreeCamera));
  92619. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92620. })(BABYLON || (BABYLON = {}));
  92621. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  92622. var BABYLON;
  92623. (function (BABYLON) {
  92624. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  92625. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92626. });
  92627. /**
  92628. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92629. */
  92630. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92631. __extends(AnaglyphGamepadCamera, _super);
  92632. /**
  92633. * Creates a new AnaglyphGamepadCamera
  92634. * @param name defines camera name
  92635. * @param position defines initial position
  92636. * @param interaxialDistance defines distance between each color axis
  92637. * @param scene defines the hosting scene
  92638. */
  92639. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92640. var _this = _super.call(this, name, position, scene) || this;
  92641. _this.interaxialDistance = interaxialDistance;
  92642. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92643. return _this;
  92644. }
  92645. /**
  92646. * Gets camera class name
  92647. * @returns AnaglyphGamepadCamera
  92648. */
  92649. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92650. return "AnaglyphGamepadCamera";
  92651. };
  92652. return AnaglyphGamepadCamera;
  92653. }(BABYLON.GamepadCamera));
  92654. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92655. })(BABYLON || (BABYLON = {}));
  92656. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  92657. var BABYLON;
  92658. (function (BABYLON) {
  92659. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  92660. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92661. });
  92662. /**
  92663. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92664. */
  92665. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92666. __extends(AnaglyphUniversalCamera, _super);
  92667. /**
  92668. * Creates a new AnaglyphUniversalCamera
  92669. * @param name defines camera name
  92670. * @param position defines initial position
  92671. * @param interaxialDistance defines distance between each color axis
  92672. * @param scene defines the hosting scene
  92673. */
  92674. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92675. var _this = _super.call(this, name, position, scene) || this;
  92676. _this.interaxialDistance = interaxialDistance;
  92677. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92678. return _this;
  92679. }
  92680. /**
  92681. * Gets camera class name
  92682. * @returns AnaglyphUniversalCamera
  92683. */
  92684. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92685. return "AnaglyphUniversalCamera";
  92686. };
  92687. return AnaglyphUniversalCamera;
  92688. }(BABYLON.UniversalCamera));
  92689. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92690. })(BABYLON || (BABYLON = {}));
  92691. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  92692. var BABYLON;
  92693. (function (BABYLON) {
  92694. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  92695. __extends(StereoscopicInterlacePostProcess, _super);
  92696. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  92697. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  92698. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92699. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92700. _this.onSizeChangedObservable.add(function () {
  92701. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92702. });
  92703. _this.onApplyObservable.add(function (effect) {
  92704. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  92705. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  92706. });
  92707. return _this;
  92708. }
  92709. return StereoscopicInterlacePostProcess;
  92710. }(BABYLON.PostProcess));
  92711. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  92712. })(BABYLON || (BABYLON = {}));
  92713. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  92714. var BABYLON;
  92715. (function (BABYLON) {
  92716. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  92717. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92718. });
  92719. /**
  92720. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92721. */
  92722. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92723. __extends(StereoscopicArcRotateCamera, _super);
  92724. /**
  92725. * Creates a new StereoscopicArcRotateCamera
  92726. * @param name defines camera name
  92727. * @param alpha defines alpha angle (in radians)
  92728. * @param beta defines beta angle (in radians)
  92729. * @param radius defines radius
  92730. * @param target defines camera target
  92731. * @param interaxialDistance defines distance between each color axis
  92732. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92733. * @param scene defines the hosting scene
  92734. */
  92735. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92736. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92737. _this.interaxialDistance = interaxialDistance;
  92738. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92739. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92740. return _this;
  92741. }
  92742. /**
  92743. * Gets camera class name
  92744. * @returns StereoscopicArcRotateCamera
  92745. */
  92746. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92747. return "StereoscopicArcRotateCamera";
  92748. };
  92749. return StereoscopicArcRotateCamera;
  92750. }(BABYLON.ArcRotateCamera));
  92751. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92752. })(BABYLON || (BABYLON = {}));
  92753. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  92754. var BABYLON;
  92755. (function (BABYLON) {
  92756. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92757. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92758. });
  92759. /**
  92760. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92761. */
  92762. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92763. __extends(StereoscopicFreeCamera, _super);
  92764. /**
  92765. * Creates a new StereoscopicFreeCamera
  92766. * @param name defines camera name
  92767. * @param position defines initial position
  92768. * @param interaxialDistance defines distance between each color axis
  92769. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92770. * @param scene defines the hosting scene
  92771. */
  92772. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92773. var _this = _super.call(this, name, position, scene) || this;
  92774. _this.interaxialDistance = interaxialDistance;
  92775. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92776. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92777. return _this;
  92778. }
  92779. /**
  92780. * Gets camera class name
  92781. * @returns StereoscopicFreeCamera
  92782. */
  92783. StereoscopicFreeCamera.prototype.getClassName = function () {
  92784. return "StereoscopicFreeCamera";
  92785. };
  92786. return StereoscopicFreeCamera;
  92787. }(BABYLON.FreeCamera));
  92788. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92789. })(BABYLON || (BABYLON = {}));
  92790. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  92791. var BABYLON;
  92792. (function (BABYLON) {
  92793. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  92794. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92795. });
  92796. /**
  92797. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92798. */
  92799. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92800. __extends(StereoscopicGamepadCamera, _super);
  92801. /**
  92802. * Creates a new StereoscopicGamepadCamera
  92803. * @param name defines camera name
  92804. * @param position defines initial position
  92805. * @param interaxialDistance defines distance between each color axis
  92806. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92807. * @param scene defines the hosting scene
  92808. */
  92809. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92810. var _this = _super.call(this, name, position, scene) || this;
  92811. _this.interaxialDistance = interaxialDistance;
  92812. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92813. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92814. return _this;
  92815. }
  92816. /**
  92817. * Gets camera class name
  92818. * @returns StereoscopicGamepadCamera
  92819. */
  92820. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92821. return "StereoscopicGamepadCamera";
  92822. };
  92823. return StereoscopicGamepadCamera;
  92824. }(BABYLON.GamepadCamera));
  92825. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92826. })(BABYLON || (BABYLON = {}));
  92827. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  92828. var BABYLON;
  92829. (function (BABYLON) {
  92830. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92831. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92832. });
  92833. /**
  92834. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92835. */
  92836. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92837. __extends(StereoscopicUniversalCamera, _super);
  92838. /**
  92839. * Creates a new StereoscopicUniversalCamera
  92840. * @param name defines camera name
  92841. * @param position defines initial position
  92842. * @param interaxialDistance defines distance between each color axis
  92843. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92844. * @param scene defines the hosting scene
  92845. */
  92846. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92847. var _this = _super.call(this, name, position, scene) || this;
  92848. _this.interaxialDistance = interaxialDistance;
  92849. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92850. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92851. return _this;
  92852. }
  92853. /**
  92854. * Gets camera class name
  92855. * @returns StereoscopicUniversalCamera
  92856. */
  92857. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92858. return "StereoscopicUniversalCamera";
  92859. };
  92860. return StereoscopicUniversalCamera;
  92861. }(BABYLON.UniversalCamera));
  92862. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92863. })(BABYLON || (BABYLON = {}));
  92864. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  92865. var BABYLON;
  92866. (function (BABYLON) {
  92867. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  92868. __extends(VRDistortionCorrectionPostProcess, _super);
  92869. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  92870. var _this = _super.call(this, name, "vrDistortionCorrection", [
  92871. 'LensCenter',
  92872. 'Scale',
  92873. 'ScaleIn',
  92874. 'HmdWarpParam'
  92875. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  92876. _this._isRightEye = isRightEye;
  92877. _this._distortionFactors = vrMetrics.distortionK;
  92878. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  92879. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  92880. _this.adaptScaleToCurrentViewport = true;
  92881. _this.onSizeChangedObservable.add(function () {
  92882. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  92883. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  92884. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  92885. });
  92886. _this.onApplyObservable.add(function (effect) {
  92887. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  92888. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  92889. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  92890. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  92891. });
  92892. return _this;
  92893. }
  92894. return VRDistortionCorrectionPostProcess;
  92895. }(BABYLON.PostProcess));
  92896. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  92897. })(BABYLON || (BABYLON = {}));
  92898. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  92899. var BABYLON;
  92900. (function (BABYLON) {
  92901. /**
  92902. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  92903. * Screen rotation is taken into account.
  92904. */
  92905. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  92906. function FreeCameraDeviceOrientationInput() {
  92907. var _this = this;
  92908. this._screenOrientationAngle = 0;
  92909. this._screenQuaternion = new BABYLON.Quaternion();
  92910. this._alpha = 0;
  92911. this._beta = 0;
  92912. this._gamma = 0;
  92913. this._orientationChanged = function () {
  92914. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  92915. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  92916. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  92917. };
  92918. this._deviceOrientation = function (evt) {
  92919. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  92920. _this._beta = evt.beta !== null ? evt.beta : 0;
  92921. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  92922. };
  92923. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  92924. this._orientationChanged();
  92925. }
  92926. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  92927. get: function () {
  92928. return this._camera;
  92929. },
  92930. set: function (camera) {
  92931. this._camera = camera;
  92932. if (this._camera != null && !this._camera.rotationQuaternion) {
  92933. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  92934. }
  92935. },
  92936. enumerable: true,
  92937. configurable: true
  92938. });
  92939. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92940. window.addEventListener("orientationchange", this._orientationChanged);
  92941. window.addEventListener("deviceorientation", this._deviceOrientation);
  92942. //In certain cases, the attach control is called AFTER orientation was changed,
  92943. //So this is needed.
  92944. this._orientationChanged();
  92945. };
  92946. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  92947. window.removeEventListener("orientationchange", this._orientationChanged);
  92948. window.removeEventListener("deviceorientation", this._deviceOrientation);
  92949. };
  92950. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  92951. //if no device orientation provided, don't update the rotation.
  92952. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  92953. if (!this._alpha)
  92954. return;
  92955. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  92956. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  92957. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  92958. //Mirror on XY Plane
  92959. this._camera.rotationQuaternion.z *= -1;
  92960. this._camera.rotationQuaternion.w *= -1;
  92961. };
  92962. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  92963. return "FreeCameraDeviceOrientationInput";
  92964. };
  92965. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  92966. return "deviceOrientation";
  92967. };
  92968. return FreeCameraDeviceOrientationInput;
  92969. }());
  92970. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  92971. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  92972. })(BABYLON || (BABYLON = {}));
  92973. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  92974. var BABYLON;
  92975. (function (BABYLON) {
  92976. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  92977. function ArcRotateCameraVRDeviceOrientationInput() {
  92978. this.alphaCorrection = 1;
  92979. this.betaCorrection = 1;
  92980. this.gammaCorrection = 1;
  92981. this._alpha = 0;
  92982. this._gamma = 0;
  92983. this._dirty = false;
  92984. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  92985. }
  92986. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92987. this.camera.attachControl(element, noPreventDefault);
  92988. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  92989. };
  92990. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  92991. if (evt.alpha !== null) {
  92992. this._alpha = +evt.alpha | 0;
  92993. }
  92994. if (evt.gamma !== null) {
  92995. this._gamma = +evt.gamma | 0;
  92996. }
  92997. this._dirty = true;
  92998. };
  92999. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  93000. if (this._dirty) {
  93001. this._dirty = false;
  93002. if (this._gamma < 0) {
  93003. this._gamma = 180 + this._gamma;
  93004. }
  93005. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  93006. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  93007. }
  93008. };
  93009. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  93010. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  93011. };
  93012. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  93013. return "ArcRotateCameraVRDeviceOrientationInput";
  93014. };
  93015. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  93016. return "VRDeviceOrientation";
  93017. };
  93018. return ArcRotateCameraVRDeviceOrientationInput;
  93019. }());
  93020. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  93021. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  93022. })(BABYLON || (BABYLON = {}));
  93023. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  93024. var BABYLON;
  93025. (function (BABYLON) {
  93026. var VRCameraMetrics = /** @class */ (function () {
  93027. function VRCameraMetrics() {
  93028. this.compensateDistortion = true;
  93029. }
  93030. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  93031. get: function () {
  93032. return this.hResolution / (2 * this.vResolution);
  93033. },
  93034. enumerable: true,
  93035. configurable: true
  93036. });
  93037. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  93038. get: function () {
  93039. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  93040. },
  93041. enumerable: true,
  93042. configurable: true
  93043. });
  93044. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  93045. get: function () {
  93046. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  93047. var h = (4 * meters) / this.hScreenSize;
  93048. return BABYLON.Matrix.Translation(h, 0, 0);
  93049. },
  93050. enumerable: true,
  93051. configurable: true
  93052. });
  93053. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  93054. get: function () {
  93055. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  93056. var h = (4 * meters) / this.hScreenSize;
  93057. return BABYLON.Matrix.Translation(-h, 0, 0);
  93058. },
  93059. enumerable: true,
  93060. configurable: true
  93061. });
  93062. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  93063. get: function () {
  93064. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  93065. },
  93066. enumerable: true,
  93067. configurable: true
  93068. });
  93069. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  93070. get: function () {
  93071. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  93072. },
  93073. enumerable: true,
  93074. configurable: true
  93075. });
  93076. VRCameraMetrics.GetDefault = function () {
  93077. var result = new VRCameraMetrics();
  93078. result.hResolution = 1280;
  93079. result.vResolution = 800;
  93080. result.hScreenSize = 0.149759993;
  93081. result.vScreenSize = 0.0935999975;
  93082. result.vScreenCenter = 0.0467999987;
  93083. result.eyeToScreenDistance = 0.0410000011;
  93084. result.lensSeparationDistance = 0.0635000020;
  93085. result.interpupillaryDistance = 0.0640000030;
  93086. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  93087. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  93088. result.postProcessScaleFactor = 1.714605507808412;
  93089. result.lensCenterOffset = 0.151976421;
  93090. return result;
  93091. };
  93092. return VRCameraMetrics;
  93093. }());
  93094. BABYLON.VRCameraMetrics = VRCameraMetrics;
  93095. })(BABYLON || (BABYLON = {}));
  93096. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  93097. var BABYLON;
  93098. (function (BABYLON) {
  93099. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  93100. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93101. });
  93102. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  93103. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93104. });
  93105. /**
  93106. * This represents a WebVR camera.
  93107. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  93108. * @example http://doc.babylonjs.com/how_to/webvr_camera
  93109. */
  93110. var WebVRFreeCamera = /** @class */ (function (_super) {
  93111. __extends(WebVRFreeCamera, _super);
  93112. /**
  93113. * Instantiates a WebVRFreeCamera.
  93114. * @param name The name of the WebVRFreeCamera
  93115. * @param position The starting anchor position for the camera
  93116. * @param scene The scene the camera belongs to
  93117. * @param webVROptions a set of customizable options for the webVRCamera
  93118. */
  93119. function WebVRFreeCamera(name, position, scene, webVROptions) {
  93120. if (webVROptions === void 0) { webVROptions = {}; }
  93121. var _this = _super.call(this, name, position, scene) || this;
  93122. _this.webVROptions = webVROptions;
  93123. /**
  93124. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  93125. */
  93126. _this._vrDevice = null;
  93127. /**
  93128. * The rawPose of the vrDevice.
  93129. */
  93130. _this.rawPose = null;
  93131. _this._specsVersion = "1.1";
  93132. _this._attached = false;
  93133. _this._descendants = [];
  93134. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  93135. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  93136. /** @hidden */
  93137. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  93138. _this._standingMatrix = null;
  93139. /**
  93140. * Represents device position in babylon space.
  93141. */
  93142. _this.devicePosition = BABYLON.Vector3.Zero();
  93143. /**
  93144. * Represents device rotation in babylon space.
  93145. */
  93146. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  93147. /**
  93148. * The scale of the device to be used when translating from device space to babylon space.
  93149. */
  93150. _this.deviceScaleFactor = 1;
  93151. _this._deviceToWorld = BABYLON.Matrix.Identity();
  93152. _this._worldToDevice = BABYLON.Matrix.Identity();
  93153. /**
  93154. * References to the webVR controllers for the vrDevice.
  93155. */
  93156. _this.controllers = [];
  93157. /**
  93158. * Emits an event when a controller is attached.
  93159. */
  93160. _this.onControllersAttachedObservable = new BABYLON.Observable();
  93161. /**
  93162. * Emits an event when a controller's mesh has been loaded;
  93163. */
  93164. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93165. /**
  93166. * Emits an event when the HMD's pose has been updated.
  93167. */
  93168. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  93169. _this._poseSet = false;
  93170. /**
  93171. * If the rig cameras be used as parent instead of this camera.
  93172. */
  93173. _this.rigParenting = true;
  93174. _this._defaultHeight = undefined;
  93175. _this._workingVector = BABYLON.Vector3.Zero();
  93176. _this._oneVector = BABYLON.Vector3.One();
  93177. _this._workingMatrix = BABYLON.Matrix.Identity();
  93178. _this._cache.position = BABYLON.Vector3.Zero();
  93179. if (webVROptions.defaultHeight) {
  93180. _this._defaultHeight = webVROptions.defaultHeight;
  93181. _this.position.y = _this._defaultHeight;
  93182. }
  93183. _this.minZ = 0.1;
  93184. //legacy support - the compensation boolean was removed.
  93185. if (arguments.length === 5) {
  93186. _this.webVROptions = arguments[4];
  93187. }
  93188. // default webVR options
  93189. if (_this.webVROptions.trackPosition == undefined) {
  93190. _this.webVROptions.trackPosition = true;
  93191. }
  93192. if (_this.webVROptions.controllerMeshes == undefined) {
  93193. _this.webVROptions.controllerMeshes = true;
  93194. }
  93195. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  93196. _this.webVROptions.defaultLightingOnControllers = true;
  93197. }
  93198. _this.rotationQuaternion = new BABYLON.Quaternion();
  93199. if (_this.webVROptions && _this.webVROptions.positionScale) {
  93200. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  93201. }
  93202. //enable VR
  93203. var engine = _this.getEngine();
  93204. _this._onVREnabled = function (success) { if (success) {
  93205. _this.initControllers();
  93206. } };
  93207. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  93208. engine.initWebVR().add(function (event) {
  93209. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  93210. return;
  93211. }
  93212. _this._vrDevice = event.vrDisplay;
  93213. //reset the rig parameters.
  93214. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  93215. if (_this._attached) {
  93216. _this.getEngine().enableVR();
  93217. }
  93218. });
  93219. if (typeof (VRFrameData) !== "undefined")
  93220. _this._frameData = new VRFrameData();
  93221. /**
  93222. * The idea behind the following lines:
  93223. * objects that have the camera as parent should actually have the rig cameras as a parent.
  93224. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  93225. * the second will not show it correctly.
  93226. *
  93227. * To solve this - each object that has the camera as parent will be added to a protected array.
  93228. * When the rig camera renders, it will take this array and set all of those to be its children.
  93229. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  93230. * Amazing!
  93231. */
  93232. scene.onBeforeCameraRenderObservable.add(function (camera) {
  93233. if (camera.parent === _this && _this.rigParenting) {
  93234. _this._descendants = _this.getDescendants(true, function (n) {
  93235. // don't take the cameras or the controllers!
  93236. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  93237. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  93238. return !isController && !isRigCamera;
  93239. });
  93240. _this._descendants.forEach(function (node) {
  93241. node.parent = camera;
  93242. });
  93243. }
  93244. });
  93245. scene.onAfterCameraRenderObservable.add(function (camera) {
  93246. if (camera.parent === _this && _this.rigParenting) {
  93247. _this._descendants.forEach(function (node) {
  93248. node.parent = _this;
  93249. });
  93250. }
  93251. });
  93252. return _this;
  93253. }
  93254. /**
  93255. * Gets the device distance from the ground in meters.
  93256. * @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.
  93257. */
  93258. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  93259. if (this._standingMatrix) {
  93260. // Add standing matrix offset to get real offset from ground in room
  93261. this._standingMatrix.getTranslationToRef(this._workingVector);
  93262. return this._deviceRoomPosition.y + this._workingVector.y;
  93263. }
  93264. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  93265. return this._defaultHeight || 0;
  93266. };
  93267. /**
  93268. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  93269. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  93270. */
  93271. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  93272. var _this = this;
  93273. if (callback === void 0) { callback = function (bool) { }; }
  93274. // Use standing matrix if available
  93275. this.getEngine().initWebVRAsync().then(function (result) {
  93276. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  93277. callback(false);
  93278. }
  93279. else {
  93280. _this._standingMatrix = new BABYLON.Matrix();
  93281. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  93282. if (!_this.getScene().useRightHandedSystem) {
  93283. [2, 6, 8, 9, 14].forEach(function (num) {
  93284. if (_this._standingMatrix) {
  93285. _this._standingMatrix.m[num] *= -1;
  93286. }
  93287. });
  93288. }
  93289. callback(true);
  93290. }
  93291. });
  93292. };
  93293. /**
  93294. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  93295. * @returns A promise with a boolean set to if the standing matrix is supported.
  93296. */
  93297. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  93298. var _this = this;
  93299. return new Promise(function (res, rej) {
  93300. _this.useStandingMatrix(function (supported) {
  93301. res(supported);
  93302. });
  93303. });
  93304. };
  93305. /**
  93306. * Disposes the camera
  93307. */
  93308. WebVRFreeCamera.prototype.dispose = function () {
  93309. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  93310. _super.prototype.dispose.call(this);
  93311. };
  93312. /**
  93313. * Gets a vrController by name.
  93314. * @param name The name of the controller to retreive
  93315. * @returns the controller matching the name specified or null if not found
  93316. */
  93317. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  93318. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  93319. var gp = _a[_i];
  93320. if (gp.hand === name) {
  93321. return gp;
  93322. }
  93323. }
  93324. return null;
  93325. };
  93326. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  93327. /**
  93328. * The controller corrisponding to the users left hand.
  93329. */
  93330. get: function () {
  93331. if (!this._leftController) {
  93332. this._leftController = this.getControllerByName("left");
  93333. }
  93334. return this._leftController;
  93335. },
  93336. enumerable: true,
  93337. configurable: true
  93338. });
  93339. ;
  93340. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  93341. /**
  93342. * The controller corrisponding to the users right hand.
  93343. */
  93344. get: function () {
  93345. if (!this._rightController) {
  93346. this._rightController = this.getControllerByName("right");
  93347. }
  93348. return this._rightController;
  93349. },
  93350. enumerable: true,
  93351. configurable: true
  93352. });
  93353. ;
  93354. /**
  93355. * Casts a ray forward from the vrCamera's gaze.
  93356. * @param length Length of the ray (default: 100)
  93357. * @returns the ray corrisponding to the gaze
  93358. */
  93359. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  93360. if (length === void 0) { length = 100; }
  93361. if (this.leftCamera) {
  93362. // Use left eye to avoid computation to compute center on every call
  93363. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  93364. }
  93365. else {
  93366. return _super.prototype.getForwardRay.call(this, length);
  93367. }
  93368. };
  93369. /**
  93370. * Updates the camera based on device's frame data
  93371. */
  93372. WebVRFreeCamera.prototype._checkInputs = function () {
  93373. if (this._vrDevice && this._vrDevice.isPresenting) {
  93374. this._vrDevice.getFrameData(this._frameData);
  93375. this.updateFromDevice(this._frameData.pose);
  93376. }
  93377. _super.prototype._checkInputs.call(this);
  93378. };
  93379. /**
  93380. * Updates the poseControlled values based on the input device pose.
  93381. * @param poseData Pose coming from the device
  93382. */
  93383. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  93384. if (poseData && poseData.orientation) {
  93385. this.rawPose = poseData;
  93386. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  93387. if (this.getScene().useRightHandedSystem) {
  93388. this._deviceRoomRotationQuaternion.z *= -1;
  93389. this._deviceRoomRotationQuaternion.w *= -1;
  93390. }
  93391. if (this.webVROptions.trackPosition && this.rawPose.position) {
  93392. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  93393. if (this.getScene().useRightHandedSystem) {
  93394. this._deviceRoomPosition.z *= -1;
  93395. }
  93396. }
  93397. this._poseSet = true;
  93398. }
  93399. };
  93400. /**
  93401. * WebVR's attach control will start broadcasting frames to the device.
  93402. * Note that in certain browsers (chrome for example) this function must be called
  93403. * within a user-interaction callback. Example:
  93404. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  93405. *
  93406. * @param element html element to attach the vrDevice to
  93407. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  93408. */
  93409. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  93410. _super.prototype.attachControl.call(this, element, noPreventDefault);
  93411. this._attached = true;
  93412. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  93413. if (this._vrDevice) {
  93414. this.getEngine().enableVR();
  93415. }
  93416. };
  93417. /**
  93418. * Detaches the camera from the html element and disables VR
  93419. *
  93420. * @param element html element to detach from
  93421. */
  93422. WebVRFreeCamera.prototype.detachControl = function (element) {
  93423. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  93424. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  93425. _super.prototype.detachControl.call(this, element);
  93426. this._attached = false;
  93427. this.getEngine().disableVR();
  93428. };
  93429. /**
  93430. * @returns the name of this class
  93431. */
  93432. WebVRFreeCamera.prototype.getClassName = function () {
  93433. return "WebVRFreeCamera";
  93434. };
  93435. /**
  93436. * Calls resetPose on the vrDisplay
  93437. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  93438. */
  93439. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  93440. //uses the vrDisplay's "resetPose()".
  93441. //pitch and roll won't be affected.
  93442. this._vrDevice.resetPose();
  93443. };
  93444. /**
  93445. * Updates the rig cameras (left and right eye)
  93446. */
  93447. WebVRFreeCamera.prototype._updateRigCameras = function () {
  93448. var camLeft = this._rigCameras[0];
  93449. var camRight = this._rigCameras[1];
  93450. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  93451. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  93452. camLeft.position.copyFrom(this._deviceRoomPosition);
  93453. camRight.position.copyFrom(this._deviceRoomPosition);
  93454. };
  93455. /**
  93456. * Updates the cached values of the camera
  93457. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  93458. */
  93459. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  93460. var _this = this;
  93461. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  93462. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  93463. if (!this.updateCacheCalled) {
  93464. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  93465. this.updateCacheCalled = true;
  93466. this.update();
  93467. }
  93468. // Set working vector to the device position in room space rotated by the new rotation
  93469. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  93470. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  93471. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  93472. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  93473. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  93474. // Add translation from anchor position
  93475. this._deviceToWorld.getTranslationToRef(this._workingVector);
  93476. this._workingVector.addInPlace(this.position);
  93477. this._workingVector.subtractInPlace(this._cache.position);
  93478. this._deviceToWorld.setTranslation(this._workingVector);
  93479. // Set an inverted matrix to be used when updating the camera
  93480. this._deviceToWorld.invertToRef(this._worldToDevice);
  93481. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  93482. this.controllers.forEach(function (controller) {
  93483. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  93484. controller.update();
  93485. });
  93486. }
  93487. if (!ignoreParentClass) {
  93488. _super.prototype._updateCache.call(this);
  93489. }
  93490. this.updateCacheCalled = false;
  93491. };
  93492. /**
  93493. * Updates the current device position and rotation in the babylon world
  93494. */
  93495. WebVRFreeCamera.prototype.update = function () {
  93496. // Get current device position in babylon world
  93497. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  93498. // Get current device rotation in babylon world
  93499. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  93500. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  93501. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  93502. if (this._poseSet) {
  93503. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  93504. }
  93505. _super.prototype.update.call(this);
  93506. };
  93507. /**
  93508. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  93509. * @returns an identity matrix
  93510. */
  93511. WebVRFreeCamera.prototype._getViewMatrix = function () {
  93512. return BABYLON.Matrix.Identity();
  93513. };
  93514. /**
  93515. * This function is called by the two RIG cameras.
  93516. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  93517. */
  93518. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  93519. var _this = this;
  93520. // Update the parent camera prior to using a child camera to avoid desynchronization
  93521. var parentCamera = this._cameraRigParams["parentCamera"];
  93522. parentCamera._updateCache();
  93523. //WebVR 1.1
  93524. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  93525. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  93526. if (!this.getScene().useRightHandedSystem) {
  93527. [2, 6, 8, 9, 14].forEach(function (num) {
  93528. _this._webvrViewMatrix.m[num] *= -1;
  93529. });
  93530. }
  93531. // update the camera rotation matrix
  93532. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  93533. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  93534. // Computing target and final matrix
  93535. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  93536. // should the view matrix be updated with scale and position offset?
  93537. if (parentCamera.deviceScaleFactor !== 1) {
  93538. this._webvrViewMatrix.invert();
  93539. // scale the position, if set
  93540. if (parentCamera.deviceScaleFactor) {
  93541. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  93542. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  93543. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  93544. }
  93545. this._webvrViewMatrix.invert();
  93546. }
  93547. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  93548. // Compute global position
  93549. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  93550. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  93551. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  93552. this._workingMatrix.getTranslationToRef(this._globalPosition);
  93553. this._markSyncedWithParent();
  93554. return this._webvrViewMatrix;
  93555. };
  93556. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  93557. var _this = this;
  93558. var parentCamera = this.parent;
  93559. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  93560. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  93561. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  93562. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  93563. //babylon compatible matrix
  93564. if (!this.getScene().useRightHandedSystem) {
  93565. [8, 9, 10, 11].forEach(function (num) {
  93566. _this._projectionMatrix.m[num] *= -1;
  93567. });
  93568. }
  93569. return this._projectionMatrix;
  93570. };
  93571. /**
  93572. * Initializes the controllers and their meshes
  93573. */
  93574. WebVRFreeCamera.prototype.initControllers = function () {
  93575. var _this = this;
  93576. this.controllers = [];
  93577. var manager = this.getScene().gamepadManager;
  93578. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  93579. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93580. var webVrController = gamepad;
  93581. if (webVrController.defaultModel) {
  93582. webVrController.defaultModel.setEnabled(false);
  93583. }
  93584. if (webVrController.hand === "right") {
  93585. _this._rightController = null;
  93586. }
  93587. if (webVrController.hand === "left") {
  93588. _this._leftController = null;
  93589. }
  93590. var controllerIndex = _this.controllers.indexOf(webVrController);
  93591. if (controllerIndex !== -1) {
  93592. _this.controllers.splice(controllerIndex, 1);
  93593. }
  93594. }
  93595. });
  93596. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  93597. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93598. var webVrController_1 = gamepad;
  93599. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  93600. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  93601. if (_this.webVROptions.controllerMeshes) {
  93602. if (webVrController_1.defaultModel) {
  93603. webVrController_1.defaultModel.setEnabled(true);
  93604. }
  93605. else {
  93606. // Load the meshes
  93607. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  93608. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  93609. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  93610. if (_this.webVROptions.defaultLightingOnControllers) {
  93611. if (!_this._lightOnControllers) {
  93612. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  93613. }
  93614. var activateLightOnSubMeshes_1 = function (mesh, light) {
  93615. var children = mesh.getChildren();
  93616. if (children.length !== 0) {
  93617. children.forEach(function (mesh) {
  93618. light.includedOnlyMeshes.push(mesh);
  93619. activateLightOnSubMeshes_1(mesh, light);
  93620. });
  93621. }
  93622. };
  93623. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  93624. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  93625. }
  93626. });
  93627. }
  93628. }
  93629. webVrController_1.attachToPoseControlledCamera(_this);
  93630. // since this is async - sanity check. Is the controller already stored?
  93631. if (_this.controllers.indexOf(webVrController_1) === -1) {
  93632. //add to the controllers array
  93633. _this.controllers.push(webVrController_1);
  93634. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  93635. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  93636. // So we're overriding setting left & right manually to be sure
  93637. var firstViveWandDetected = false;
  93638. for (var i = 0; i < _this.controllers.length; i++) {
  93639. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93640. if (!firstViveWandDetected) {
  93641. firstViveWandDetected = true;
  93642. _this.controllers[i].hand = "left";
  93643. }
  93644. else {
  93645. _this.controllers[i].hand = "right";
  93646. }
  93647. }
  93648. }
  93649. //did we find enough controllers? Great! let the developer know.
  93650. if (_this.controllers.length >= 2) {
  93651. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  93652. }
  93653. }
  93654. }
  93655. });
  93656. };
  93657. return WebVRFreeCamera;
  93658. }(BABYLON.FreeCamera));
  93659. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  93660. })(BABYLON || (BABYLON = {}));
  93661. //# sourceMappingURL=babylon.webVRCamera.js.map
  93662. var BABYLON;
  93663. (function (BABYLON) {
  93664. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  93665. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  93666. });
  93667. // We're mainly based on the logic defined into the FreeCamera code
  93668. /**
  93669. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  93670. * being tilted forward or back and left or right.
  93671. */
  93672. var DeviceOrientationCamera = /** @class */ (function (_super) {
  93673. __extends(DeviceOrientationCamera, _super);
  93674. /**
  93675. * Creates a new device orientation camera
  93676. * @param name The name of the camera
  93677. * @param position The start position camera
  93678. * @param scene The scene the camera belongs to
  93679. */
  93680. function DeviceOrientationCamera(name, position, scene) {
  93681. var _this = _super.call(this, name, position, scene) || this;
  93682. _this._quaternionCache = new BABYLON.Quaternion();
  93683. _this.inputs.addDeviceOrientation();
  93684. return _this;
  93685. }
  93686. /**
  93687. * Gets the current instance class name ("DeviceOrientationCamera").
  93688. * This helps avoiding instanceof at run time.
  93689. * @returns the class name
  93690. */
  93691. DeviceOrientationCamera.prototype.getClassName = function () {
  93692. return "DeviceOrientationCamera";
  93693. };
  93694. /**
  93695. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  93696. */
  93697. DeviceOrientationCamera.prototype._checkInputs = function () {
  93698. _super.prototype._checkInputs.call(this);
  93699. this._quaternionCache.copyFrom(this.rotationQuaternion);
  93700. if (this._initialQuaternion) {
  93701. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93702. }
  93703. };
  93704. /**
  93705. * Reset the camera to its default orientation on the specified axis only.
  93706. * @param axis The axis to reset
  93707. */
  93708. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  93709. var _this = this;
  93710. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  93711. //can only work if this camera has a rotation quaternion already.
  93712. if (!this.rotationQuaternion)
  93713. return;
  93714. if (!this._initialQuaternion) {
  93715. this._initialQuaternion = new BABYLON.Quaternion();
  93716. }
  93717. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  93718. ['x', 'y', 'z'].forEach(function (axisName) {
  93719. if (!axis[axisName]) {
  93720. _this._initialQuaternion[axisName] = 0;
  93721. }
  93722. else {
  93723. _this._initialQuaternion[axisName] *= -1;
  93724. }
  93725. });
  93726. this._initialQuaternion.normalize();
  93727. //force rotation update
  93728. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93729. };
  93730. return DeviceOrientationCamera;
  93731. }(BABYLON.FreeCamera));
  93732. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  93733. })(BABYLON || (BABYLON = {}));
  93734. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  93735. var BABYLON;
  93736. (function (BABYLON) {
  93737. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93738. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93739. });
  93740. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  93741. __extends(VRDeviceOrientationFreeCamera, _super);
  93742. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93743. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93744. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93745. var _this = _super.call(this, name, position, scene) || this;
  93746. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93747. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93748. return _this;
  93749. }
  93750. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  93751. return "VRDeviceOrientationFreeCamera";
  93752. };
  93753. return VRDeviceOrientationFreeCamera;
  93754. }(BABYLON.DeviceOrientationCamera));
  93755. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  93756. })(BABYLON || (BABYLON = {}));
  93757. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  93758. var BABYLON;
  93759. (function (BABYLON) {
  93760. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93761. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  93762. });
  93763. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  93764. __extends(VRDeviceOrientationArcRotateCamera, _super);
  93765. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  93766. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93767. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93768. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93769. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93770. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93771. _this.inputs.addVRDeviceOrientation();
  93772. return _this;
  93773. }
  93774. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  93775. return "VRDeviceOrientationArcRotateCamera";
  93776. };
  93777. return VRDeviceOrientationArcRotateCamera;
  93778. }(BABYLON.ArcRotateCamera));
  93779. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  93780. })(BABYLON || (BABYLON = {}));
  93781. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  93782. var BABYLON;
  93783. (function (BABYLON) {
  93784. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  93785. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  93786. });
  93787. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  93788. __extends(VRDeviceOrientationGamepadCamera, _super);
  93789. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93790. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93791. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93792. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  93793. _this.inputs.addGamepad();
  93794. return _this;
  93795. }
  93796. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  93797. return "VRDeviceOrientationGamepadCamera";
  93798. };
  93799. return VRDeviceOrientationGamepadCamera;
  93800. }(BABYLON.VRDeviceOrientationFreeCamera));
  93801. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  93802. })(BABYLON || (BABYLON = {}));
  93803. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  93804. var BABYLON;
  93805. (function (BABYLON) {
  93806. var VRExperienceHelperGazer = /** @class */ (function () {
  93807. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  93808. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  93809. this.scene = scene;
  93810. this._pointerDownOnMeshAsked = false;
  93811. this._isActionableMesh = false;
  93812. this._teleportationRequestInitiated = false;
  93813. this._teleportationBackRequestInitiated = false;
  93814. this._rotationRightAsked = false;
  93815. this._rotationLeftAsked = false;
  93816. this._dpadPressed = true;
  93817. this._activePointer = false;
  93818. this._id = VRExperienceHelperGazer._idCounter++;
  93819. // Gaze tracker
  93820. if (!gazeTrackerToClone) {
  93821. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  93822. this._gazeTracker.bakeCurrentTransformIntoVertices();
  93823. this._gazeTracker.isPickable = false;
  93824. this._gazeTracker.isVisible = false;
  93825. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  93826. targetMat.specularColor = BABYLON.Color3.Black();
  93827. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93828. targetMat.backFaceCulling = false;
  93829. this._gazeTracker.material = targetMat;
  93830. }
  93831. else {
  93832. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  93833. }
  93834. }
  93835. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  93836. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  93837. };
  93838. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  93839. this._pointerDownOnMeshAsked = true;
  93840. if (this._currentHit) {
  93841. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  93842. }
  93843. };
  93844. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  93845. if (this._currentHit) {
  93846. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  93847. }
  93848. this._pointerDownOnMeshAsked = false;
  93849. };
  93850. VRExperienceHelperGazer.prototype._activatePointer = function () {
  93851. this._activePointer = true;
  93852. };
  93853. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  93854. this._activePointer = false;
  93855. };
  93856. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  93857. if (distance === void 0) { distance = 100; }
  93858. };
  93859. VRExperienceHelperGazer.prototype.dispose = function () {
  93860. this._interactionsEnabled = false;
  93861. this._teleportationEnabled = false;
  93862. if (this._gazeTracker) {
  93863. this._gazeTracker.dispose();
  93864. }
  93865. };
  93866. VRExperienceHelperGazer._idCounter = 0;
  93867. return VRExperienceHelperGazer;
  93868. }());
  93869. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  93870. __extends(VRExperienceHelperControllerGazer, _super);
  93871. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  93872. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  93873. _this.webVRController = webVRController;
  93874. // Laser pointer
  93875. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  93876. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  93877. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93878. laserPointerMaterial.alpha = 0.6;
  93879. _this._laserPointer.material = laserPointerMaterial;
  93880. _this._laserPointer.rotation.x = Math.PI / 2;
  93881. _this._laserPointer.position.z = -0.5;
  93882. _this._laserPointer.isVisible = false;
  93883. _this._laserPointer.isPickable = false;
  93884. if (!webVRController.mesh) {
  93885. // Create an empty mesh that is used prior to loading the high quality model
  93886. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  93887. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  93888. preloadPointerPose.rotation.x = -0.7;
  93889. preloadMesh.addChild(preloadPointerPose);
  93890. webVRController.attachToMesh(preloadMesh);
  93891. }
  93892. _this._setLaserPointerParent(webVRController.mesh);
  93893. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  93894. _this._setLaserPointerParent(mesh);
  93895. });
  93896. return _this;
  93897. }
  93898. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  93899. return this.webVRController.getForwardRay(length);
  93900. };
  93901. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  93902. _super.prototype._activatePointer.call(this);
  93903. this._laserPointer.isVisible = true;
  93904. };
  93905. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  93906. _super.prototype._deactivatePointer.call(this);
  93907. this._laserPointer.isVisible = false;
  93908. };
  93909. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  93910. this._laserPointer.material.emissiveColor = color;
  93911. };
  93912. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  93913. var makeNotPick = function (root) {
  93914. root.isPickable = false;
  93915. root.getChildMeshes().forEach(function (c) {
  93916. makeNotPick(c);
  93917. });
  93918. };
  93919. makeNotPick(mesh);
  93920. var childMeshes = mesh.getChildMeshes();
  93921. this.webVRController._pointingPoseNode = null;
  93922. for (var i = 0; i < childMeshes.length; i++) {
  93923. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  93924. mesh = childMeshes[i];
  93925. this.webVRController._pointingPoseNode = mesh;
  93926. break;
  93927. }
  93928. }
  93929. this._laserPointer.parent = mesh;
  93930. };
  93931. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  93932. if (distance === void 0) { distance = 100; }
  93933. this._laserPointer.scaling.y = distance;
  93934. this._laserPointer.position.z = -distance / 2;
  93935. };
  93936. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  93937. _super.prototype.dispose.call(this);
  93938. this._laserPointer.dispose();
  93939. if (this._meshAttachedObserver) {
  93940. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  93941. }
  93942. };
  93943. return VRExperienceHelperControllerGazer;
  93944. }(VRExperienceHelperGazer));
  93945. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  93946. __extends(VRExperienceHelperCameraGazer, _super);
  93947. function VRExperienceHelperCameraGazer(getCamera, scene) {
  93948. var _this = _super.call(this, scene) || this;
  93949. _this.getCamera = getCamera;
  93950. return _this;
  93951. }
  93952. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  93953. var camera = this.getCamera();
  93954. if (camera) {
  93955. return camera.getForwardRay(length);
  93956. }
  93957. else {
  93958. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  93959. }
  93960. };
  93961. return VRExperienceHelperCameraGazer;
  93962. }(VRExperienceHelperGazer));
  93963. /**
  93964. * Helps to quickly add VR support to an existing scene.
  93965. * See http://doc.babylonjs.com/how_to/webvr_helper
  93966. */
  93967. var VRExperienceHelper = /** @class */ (function () {
  93968. /**
  93969. * Instantiates a VRExperienceHelper.
  93970. * Helps to quickly add VR support to an existing scene.
  93971. * @param scene The scene the VRExperienceHelper belongs to.
  93972. * @param webVROptions Options to modify the vr experience helper's behavior.
  93973. */
  93974. function VRExperienceHelper(scene,
  93975. /** Options to modify the vr experience helper's behavior. */
  93976. webVROptions) {
  93977. if (webVROptions === void 0) { webVROptions = {}; }
  93978. var _this = this;
  93979. this.webVROptions = webVROptions;
  93980. // Can the system support WebVR, even if a headset isn't plugged in?
  93981. this._webVRsupported = false;
  93982. // If WebVR is supported, is a headset plugged in and are we ready to present?
  93983. this._webVRready = false;
  93984. // Are we waiting for the requestPresent callback to complete?
  93985. this._webVRrequesting = false;
  93986. // Are we presenting to the headset right now?
  93987. this._webVRpresenting = false;
  93988. // Are we presenting in the fullscreen fallback?
  93989. this._fullscreenVRpresenting = false;
  93990. /**
  93991. * Observable raised when entering VR.
  93992. */
  93993. this.onEnteringVRObservable = new BABYLON.Observable();
  93994. /**
  93995. * Observable raised when exiting VR.
  93996. */
  93997. this.onExitingVRObservable = new BABYLON.Observable();
  93998. /**
  93999. * Observable raised when controller mesh is loaded.
  94000. */
  94001. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  94002. this._useCustomVRButton = false;
  94003. this._teleportationRequested = false;
  94004. this._teleportActive = false;
  94005. this._floorMeshesCollection = [];
  94006. this._rotationAllowed = true;
  94007. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  94008. this._isDefaultTeleportationTarget = true;
  94009. this._teleportationFillColor = "#444444";
  94010. this._teleportationBorderColor = "#FFFFFF";
  94011. this._rotationAngle = 0;
  94012. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  94013. this._padSensibilityUp = 0.65;
  94014. this._padSensibilityDown = 0.35;
  94015. this.leftController = null;
  94016. this.rightController = null;
  94017. /**
  94018. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  94019. */
  94020. this.onNewMeshSelected = new BABYLON.Observable();
  94021. /**
  94022. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  94023. */
  94024. this.onNewMeshPicked = new BABYLON.Observable();
  94025. /**
  94026. * Observable raised before camera teleportation
  94027. */
  94028. this.onBeforeCameraTeleport = new BABYLON.Observable();
  94029. /**
  94030. * Observable raised after camera teleportation
  94031. */
  94032. this.onAfterCameraTeleport = new BABYLON.Observable();
  94033. /**
  94034. * Observable raised when current selected mesh gets unselected
  94035. */
  94036. this.onSelectedMeshUnselected = new BABYLON.Observable();
  94037. /**
  94038. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  94039. */
  94040. this.teleportationEnabled = true;
  94041. this._teleportationInitialized = false;
  94042. this._interactionsEnabled = false;
  94043. this._interactionsRequested = false;
  94044. this._displayGaze = true;
  94045. this._displayLaserPointer = true;
  94046. this._onResize = function () {
  94047. _this.moveButtonToBottomRight();
  94048. if (_this._fullscreenVRpresenting && _this._webVRready) {
  94049. _this.exitVR();
  94050. }
  94051. };
  94052. this._onFullscreenChange = function () {
  94053. if (document.fullscreen !== undefined) {
  94054. _this._fullscreenVRpresenting = document.fullscreen;
  94055. }
  94056. else if (document.mozFullScreen !== undefined) {
  94057. _this._fullscreenVRpresenting = document.mozFullScreen;
  94058. }
  94059. else if (document.webkitIsFullScreen !== undefined) {
  94060. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  94061. }
  94062. else if (document.msIsFullScreen !== undefined) {
  94063. _this._fullscreenVRpresenting = document.msIsFullScreen;
  94064. }
  94065. else if (document.msFullscreenElement !== undefined) {
  94066. _this._fullscreenVRpresenting = document.msFullscreenElement;
  94067. }
  94068. if (!_this._fullscreenVRpresenting && _this._canvas) {
  94069. _this.exitVR();
  94070. if (!_this._useCustomVRButton) {
  94071. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  94072. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  94073. }
  94074. }
  94075. };
  94076. this.beforeRender = function () {
  94077. if (_this.leftController && _this.leftController._activePointer) {
  94078. _this._castRayAndSelectObject(_this.leftController);
  94079. }
  94080. if (_this.rightController && _this.rightController._activePointer) {
  94081. _this._castRayAndSelectObject(_this.rightController);
  94082. }
  94083. if (_this._noControllerIsActive) {
  94084. _this._castRayAndSelectObject(_this._cameraGazer);
  94085. }
  94086. else {
  94087. _this._cameraGazer._gazeTracker.isVisible = false;
  94088. }
  94089. };
  94090. this._onNewGamepadConnected = function (gamepad) {
  94091. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  94092. if (gamepad.leftStick) {
  94093. gamepad.onleftstickchanged(function (stickValues) {
  94094. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  94095. // Listening to classic/xbox gamepad only if no VR controller is active
  94096. if ((!_this.leftController && !_this.rightController) ||
  94097. ((_this.leftController && !_this.leftController._activePointer) &&
  94098. (_this.rightController && !_this.rightController._activePointer))) {
  94099. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  94100. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  94101. }
  94102. }
  94103. });
  94104. }
  94105. if (gamepad.rightStick) {
  94106. gamepad.onrightstickchanged(function (stickValues) {
  94107. if (_this._teleportationInitialized) {
  94108. _this._checkRotate(stickValues, _this._cameraGazer);
  94109. }
  94110. });
  94111. }
  94112. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  94113. gamepad.onbuttondown(function (buttonPressed) {
  94114. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  94115. _this._cameraGazer._selectionPointerDown();
  94116. }
  94117. });
  94118. gamepad.onbuttonup(function (buttonPressed) {
  94119. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  94120. _this._cameraGazer._selectionPointerUp();
  94121. }
  94122. });
  94123. }
  94124. }
  94125. else {
  94126. var webVRController = gamepad;
  94127. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  94128. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  94129. _this.rightController = controller;
  94130. }
  94131. else {
  94132. _this.leftController = controller;
  94133. }
  94134. _this._tryEnableInteractionOnController(controller);
  94135. }
  94136. };
  94137. // 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
  94138. this._tryEnableInteractionOnController = function (controller) {
  94139. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  94140. _this._enableInteractionOnController(controller);
  94141. }
  94142. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  94143. _this._enableTeleportationOnController(controller);
  94144. }
  94145. };
  94146. this._onNewGamepadDisconnected = function (gamepad) {
  94147. if (gamepad instanceof BABYLON.WebVRController) {
  94148. if (gamepad.hand === "left" && _this.leftController != null) {
  94149. _this.leftController.dispose();
  94150. _this.leftController = null;
  94151. }
  94152. if (gamepad.hand === "right" && _this.rightController != null) {
  94153. _this.rightController.dispose();
  94154. _this.rightController = null;
  94155. }
  94156. }
  94157. };
  94158. this._workingVector = BABYLON.Vector3.Zero();
  94159. this._workingQuaternion = BABYLON.Quaternion.Identity();
  94160. this._workingMatrix = BABYLON.Matrix.Identity();
  94161. this._scene = scene;
  94162. this._canvas = scene.getEngine().getRenderingCanvas();
  94163. // Parse options
  94164. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  94165. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  94166. }
  94167. if (webVROptions.createDeviceOrientationCamera === undefined) {
  94168. webVROptions.createDeviceOrientationCamera = true;
  94169. }
  94170. if (webVROptions.laserToggle === undefined) {
  94171. webVROptions.laserToggle = true;
  94172. }
  94173. if (webVROptions.defaultHeight === undefined) {
  94174. webVROptions.defaultHeight = 1.7;
  94175. }
  94176. if (webVROptions.useCustomVRButton) {
  94177. this._useCustomVRButton = true;
  94178. if (webVROptions.customVRButton) {
  94179. this._btnVR = webVROptions.customVRButton;
  94180. }
  94181. }
  94182. if (webVROptions.rayLength) {
  94183. this._rayLength = webVROptions.rayLength;
  94184. }
  94185. this._defaultHeight = webVROptions.defaultHeight;
  94186. if (webVROptions.positionScale) {
  94187. this._rayLength *= webVROptions.positionScale;
  94188. this._defaultHeight *= webVROptions.positionScale;
  94189. }
  94190. // Set position
  94191. if (this._scene.activeCamera) {
  94192. this._position = this._scene.activeCamera.position.clone();
  94193. }
  94194. else {
  94195. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  94196. }
  94197. // Set non-vr camera
  94198. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  94199. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  94200. // Copy data from existing camera
  94201. if (this._scene.activeCamera) {
  94202. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94203. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  94204. // Set rotation from previous camera
  94205. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  94206. var targetCamera = this._scene.activeCamera;
  94207. if (targetCamera.rotationQuaternion) {
  94208. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  94209. }
  94210. else {
  94211. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  94212. }
  94213. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  94214. }
  94215. }
  94216. this._scene.activeCamera = this._deviceOrientationCamera;
  94217. if (this._canvas) {
  94218. this._scene.activeCamera.attachControl(this._canvas);
  94219. }
  94220. }
  94221. else {
  94222. this._existingCamera = this._scene.activeCamera;
  94223. }
  94224. // Create VR cameras
  94225. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  94226. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  94227. }
  94228. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  94229. this._webVRCamera.useStandingMatrix();
  94230. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  94231. // Create default button
  94232. if (!this._useCustomVRButton) {
  94233. this._btnVR = document.createElement("BUTTON");
  94234. this._btnVR.className = "babylonVRicon";
  94235. this._btnVR.id = "babylonVRiconbtn";
  94236. this._btnVR.title = "Click to switch to VR";
  94237. 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) }";
  94238. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  94239. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  94240. // css += ".babylonVRicon.vrdisplaysupported { }";
  94241. // css += ".babylonVRicon.vrdisplayready { }";
  94242. // css += ".babylonVRicon.vrdisplayrequesting { }";
  94243. var style = document.createElement('style');
  94244. style.appendChild(document.createTextNode(css));
  94245. document.getElementsByTagName('head')[0].appendChild(style);
  94246. this.moveButtonToBottomRight();
  94247. }
  94248. // VR button click event
  94249. if (this._btnVR) {
  94250. this._btnVR.addEventListener("click", function () {
  94251. if (!_this.isInVRMode) {
  94252. _this.enterVR();
  94253. }
  94254. else {
  94255. _this.exitVR();
  94256. }
  94257. });
  94258. }
  94259. // Window events
  94260. window.addEventListener("resize", this._onResize);
  94261. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  94262. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  94263. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  94264. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  94265. document.onmsfullscreenchange = this._onFullscreenChange;
  94266. // Display vr button when headset is connected
  94267. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  94268. this.displayVRButton();
  94269. }
  94270. else {
  94271. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  94272. if (e.vrDisplay) {
  94273. _this.displayVRButton();
  94274. }
  94275. });
  94276. }
  94277. // Exiting VR mode using 'ESC' key on desktop
  94278. this._onKeyDown = function (event) {
  94279. if (event.keyCode === 27 && _this.isInVRMode) {
  94280. _this.exitVR();
  94281. }
  94282. };
  94283. document.addEventListener("keydown", this._onKeyDown);
  94284. // Exiting VR mode double tapping the touch screen
  94285. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  94286. if (_this.isInVRMode) {
  94287. _this.exitVR();
  94288. if (_this._fullscreenVRpresenting) {
  94289. _this._scene.getEngine().switchFullscreen(true);
  94290. }
  94291. }
  94292. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  94293. // Listen for WebVR display changes
  94294. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  94295. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  94296. this._onVRRequestPresentStart = function () {
  94297. _this._webVRrequesting = true;
  94298. _this.updateButtonVisibility();
  94299. };
  94300. this._onVRRequestPresentComplete = function (success) {
  94301. _this._webVRrequesting = false;
  94302. _this.updateButtonVisibility();
  94303. };
  94304. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  94305. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  94306. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  94307. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94308. scene.onDisposeObservable.add(function () {
  94309. _this.dispose();
  94310. });
  94311. // Gamepad connection events
  94312. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  94313. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  94314. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  94315. this.updateButtonVisibility();
  94316. //create easing functions
  94317. this._circleEase = new BABYLON.CircleEase();
  94318. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94319. if (this.webVROptions.floorMeshes) {
  94320. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  94321. }
  94322. }
  94323. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  94324. /** Return this.onEnteringVRObservable
  94325. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  94326. */
  94327. get: function () {
  94328. return this.onEnteringVRObservable;
  94329. },
  94330. enumerable: true,
  94331. configurable: true
  94332. });
  94333. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  94334. /** Return this.onExitingVRObservable
  94335. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  94336. */
  94337. get: function () {
  94338. return this.onExitingVRObservable;
  94339. },
  94340. enumerable: true,
  94341. configurable: true
  94342. });
  94343. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  94344. /** Return this.onControllerMeshLoadedObservable
  94345. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  94346. */
  94347. get: function () {
  94348. return this.onControllerMeshLoadedObservable;
  94349. },
  94350. enumerable: true,
  94351. configurable: true
  94352. });
  94353. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  94354. /**
  94355. * The mesh used to display where the user is going to teleport.
  94356. */
  94357. get: function () {
  94358. return this._teleportationTarget;
  94359. },
  94360. /**
  94361. * Sets the mesh to be used to display where the user is going to teleport.
  94362. */
  94363. set: function (value) {
  94364. if (value) {
  94365. value.name = "teleportationTarget";
  94366. this._isDefaultTeleportationTarget = false;
  94367. this._teleportationTarget = value;
  94368. }
  94369. },
  94370. enumerable: true,
  94371. configurable: true
  94372. });
  94373. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  94374. /**
  94375. * The mesh used to display where the user is selecting,
  94376. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  94377. * See http://doc.babylonjs.com/resources/baking_transformations
  94378. */
  94379. get: function () {
  94380. return this._cameraGazer._gazeTracker;
  94381. },
  94382. set: function (value) {
  94383. if (value) {
  94384. this._cameraGazer._gazeTracker = value;
  94385. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  94386. this._cameraGazer._gazeTracker.isPickable = false;
  94387. this._cameraGazer._gazeTracker.isVisible = false;
  94388. this._cameraGazer._gazeTracker.name = "gazeTracker";
  94389. if (this.leftController) {
  94390. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  94391. }
  94392. if (this.rightController) {
  94393. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  94394. }
  94395. }
  94396. },
  94397. enumerable: true,
  94398. configurable: true
  94399. });
  94400. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  94401. /**
  94402. * If the ray of the gaze should be displayed.
  94403. */
  94404. get: function () {
  94405. return this._displayGaze;
  94406. },
  94407. /**
  94408. * Sets if the ray of the gaze should be displayed.
  94409. */
  94410. set: function (value) {
  94411. this._displayGaze = value;
  94412. if (!value) {
  94413. this._cameraGazer._gazeTracker.isVisible = false;
  94414. if (this.leftController) {
  94415. this.leftController._gazeTracker.isVisible = false;
  94416. }
  94417. if (this.rightController) {
  94418. this.rightController._gazeTracker.isVisible = false;
  94419. }
  94420. }
  94421. },
  94422. enumerable: true,
  94423. configurable: true
  94424. });
  94425. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  94426. /**
  94427. * If the ray of the LaserPointer should be displayed.
  94428. */
  94429. get: function () {
  94430. return this._displayLaserPointer;
  94431. },
  94432. /**
  94433. * Sets if the ray of the LaserPointer should be displayed.
  94434. */
  94435. set: function (value) {
  94436. this._displayLaserPointer = value;
  94437. if (!value) {
  94438. if (this.rightController) {
  94439. this.rightController._deactivatePointer();
  94440. this.rightController._gazeTracker.isVisible = false;
  94441. }
  94442. if (this.leftController) {
  94443. this.leftController._deactivatePointer();
  94444. this.leftController._gazeTracker.isVisible = false;
  94445. }
  94446. }
  94447. else {
  94448. if (this.rightController) {
  94449. this.rightController._activatePointer();
  94450. }
  94451. if (this.leftController) {
  94452. this.leftController._activatePointer();
  94453. }
  94454. }
  94455. },
  94456. enumerable: true,
  94457. configurable: true
  94458. });
  94459. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  94460. /**
  94461. * The deviceOrientationCamera used as the camera when not in VR.
  94462. */
  94463. get: function () {
  94464. return this._deviceOrientationCamera;
  94465. },
  94466. enumerable: true,
  94467. configurable: true
  94468. });
  94469. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  94470. /**
  94471. * Based on the current WebVR support, returns the current VR camera used.
  94472. */
  94473. get: function () {
  94474. if (this._webVRready) {
  94475. return this._webVRCamera;
  94476. }
  94477. else {
  94478. return this._scene.activeCamera;
  94479. }
  94480. },
  94481. enumerable: true,
  94482. configurable: true
  94483. });
  94484. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  94485. /**
  94486. * The webVRCamera which is used when in VR.
  94487. */
  94488. get: function () {
  94489. return this._webVRCamera;
  94490. },
  94491. enumerable: true,
  94492. configurable: true
  94493. });
  94494. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  94495. /**
  94496. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  94497. */
  94498. get: function () {
  94499. return this._vrDeviceOrientationCamera;
  94500. },
  94501. enumerable: true,
  94502. configurable: true
  94503. });
  94504. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  94505. get: function () {
  94506. var result = this._cameraGazer._teleportationRequestInitiated
  94507. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  94508. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  94509. return result;
  94510. },
  94511. enumerable: true,
  94512. configurable: true
  94513. });
  94514. // Raised when one of the controller has loaded successfully its associated default mesh
  94515. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  94516. if (this.leftController && this.leftController.webVRController == webVRController) {
  94517. if (webVRController.mesh) {
  94518. this.leftController._setLaserPointerParent(webVRController.mesh);
  94519. }
  94520. }
  94521. if (this.rightController && this.rightController.webVRController == webVRController) {
  94522. if (webVRController.mesh) {
  94523. this.rightController._setLaserPointerParent(webVRController.mesh);
  94524. }
  94525. }
  94526. try {
  94527. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  94528. }
  94529. catch (err) {
  94530. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  94531. }
  94532. };
  94533. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  94534. /**
  94535. * Gets a value indicating if we are currently in VR mode.
  94536. */
  94537. get: function () {
  94538. return this._webVRpresenting || this._fullscreenVRpresenting;
  94539. },
  94540. enumerable: true,
  94541. configurable: true
  94542. });
  94543. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  94544. var vrDisplay = this._scene.getEngine().getVRDevice();
  94545. if (vrDisplay) {
  94546. var wasPresenting = this._webVRpresenting;
  94547. // A VR display is connected
  94548. this._webVRpresenting = vrDisplay.isPresenting;
  94549. if (wasPresenting && !this._webVRpresenting)
  94550. this.exitVR();
  94551. }
  94552. else {
  94553. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  94554. }
  94555. this.updateButtonVisibility();
  94556. };
  94557. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  94558. this._webVRsupported = eventArgs.vrSupported;
  94559. this._webVRready = !!eventArgs.vrDisplay;
  94560. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  94561. this.updateButtonVisibility();
  94562. };
  94563. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  94564. if (this._canvas && !this._useCustomVRButton) {
  94565. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  94566. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  94567. }
  94568. };
  94569. VRExperienceHelper.prototype.displayVRButton = function () {
  94570. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  94571. document.body.appendChild(this._btnVR);
  94572. this._btnVRDisplayed = true;
  94573. }
  94574. };
  94575. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  94576. if (!this._btnVR || this._useCustomVRButton) {
  94577. return;
  94578. }
  94579. this._btnVR.className = "babylonVRicon";
  94580. if (this.isInVRMode) {
  94581. this._btnVR.className += " vrdisplaypresenting";
  94582. }
  94583. else {
  94584. if (this._webVRready)
  94585. this._btnVR.className += " vrdisplayready";
  94586. if (this._webVRsupported)
  94587. this._btnVR.className += " vrdisplaysupported";
  94588. if (this._webVRrequesting)
  94589. this._btnVR.className += " vrdisplayrequesting";
  94590. }
  94591. };
  94592. /**
  94593. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  94594. * Otherwise, will use the fullscreen API.
  94595. */
  94596. VRExperienceHelper.prototype.enterVR = function () {
  94597. if (this.onEnteringVRObservable) {
  94598. try {
  94599. this.onEnteringVRObservable.notifyObservers(this);
  94600. }
  94601. catch (err) {
  94602. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  94603. }
  94604. }
  94605. if (this._scene.activeCamera) {
  94606. this._position = this._scene.activeCamera.position.clone();
  94607. // make sure that we return to the last active camera
  94608. this._existingCamera = this._scene.activeCamera;
  94609. }
  94610. if (this._webVRrequesting)
  94611. return;
  94612. // If WebVR is supported and a headset is connected
  94613. if (this._webVRready) {
  94614. if (!this._webVRpresenting) {
  94615. this._webVRCamera.position = this._position;
  94616. this._scene.activeCamera = this._webVRCamera;
  94617. }
  94618. }
  94619. else if (this._vrDeviceOrientationCamera) {
  94620. this._vrDeviceOrientationCamera.position = this._position;
  94621. if (this._scene.activeCamera) {
  94622. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94623. }
  94624. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  94625. this._scene.getEngine().switchFullscreen(true);
  94626. this.updateButtonVisibility();
  94627. }
  94628. if (this._scene.activeCamera && this._canvas) {
  94629. this._scene.activeCamera.attachControl(this._canvas);
  94630. }
  94631. if (this._interactionsEnabled) {
  94632. this._scene.registerBeforeRender(this.beforeRender);
  94633. }
  94634. };
  94635. /**
  94636. * Attempt to exit VR, or fullscreen.
  94637. */
  94638. VRExperienceHelper.prototype.exitVR = function () {
  94639. if (this.onExitingVRObservable) {
  94640. try {
  94641. this.onExitingVRObservable.notifyObservers(this);
  94642. }
  94643. catch (err) {
  94644. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  94645. }
  94646. }
  94647. if (this._webVRpresenting) {
  94648. this._scene.getEngine().disableVR();
  94649. }
  94650. if (this._scene.activeCamera) {
  94651. this._position = this._scene.activeCamera.position.clone();
  94652. }
  94653. if (this._deviceOrientationCamera) {
  94654. this._deviceOrientationCamera.position = this._position;
  94655. this._scene.activeCamera = this._deviceOrientationCamera;
  94656. if (this._canvas) {
  94657. this._scene.activeCamera.attachControl(this._canvas);
  94658. }
  94659. }
  94660. else if (this._existingCamera) {
  94661. this._existingCamera.position = this._position;
  94662. this._scene.activeCamera = this._existingCamera;
  94663. }
  94664. this.updateButtonVisibility();
  94665. if (this._interactionsEnabled) {
  94666. this._scene.unregisterBeforeRender(this.beforeRender);
  94667. }
  94668. // resize to update width and height when exiting vr exits fullscreen
  94669. this._scene.getEngine().resize();
  94670. };
  94671. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  94672. /**
  94673. * The position of the vr experience helper.
  94674. */
  94675. get: function () {
  94676. return this._position;
  94677. },
  94678. /**
  94679. * Sets the position of the vr experience helper.
  94680. */
  94681. set: function (value) {
  94682. this._position = value;
  94683. if (this._scene.activeCamera) {
  94684. this._scene.activeCamera.position = value;
  94685. }
  94686. },
  94687. enumerable: true,
  94688. configurable: true
  94689. });
  94690. /**
  94691. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  94692. */
  94693. VRExperienceHelper.prototype.enableInteractions = function () {
  94694. var _this = this;
  94695. if (!this._interactionsEnabled) {
  94696. this._interactionsRequested = true;
  94697. if (this.leftController) {
  94698. this._enableInteractionOnController(this.leftController);
  94699. }
  94700. if (this.rightController) {
  94701. this._enableInteractionOnController(this.rightController);
  94702. }
  94703. this.raySelectionPredicate = function (mesh) {
  94704. return mesh.isVisible && mesh.isPickable;
  94705. };
  94706. this.meshSelectionPredicate = function (mesh) {
  94707. return true;
  94708. };
  94709. this._raySelectionPredicate = function (mesh) {
  94710. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  94711. && mesh.name.indexOf("teleportationTarget") === -1
  94712. && mesh.name.indexOf("torusTeleportation") === -1)) {
  94713. return _this.raySelectionPredicate(mesh);
  94714. }
  94715. return false;
  94716. };
  94717. this._interactionsEnabled = true;
  94718. }
  94719. };
  94720. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  94721. get: function () {
  94722. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  94723. },
  94724. enumerable: true,
  94725. configurable: true
  94726. });
  94727. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  94728. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  94729. if (this._floorMeshesCollection[i].id === mesh.id) {
  94730. return true;
  94731. }
  94732. }
  94733. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  94734. return true;
  94735. }
  94736. return false;
  94737. };
  94738. /**
  94739. * Adds a floor mesh to be used for teleportation.
  94740. * @param floorMesh the mesh to be used for teleportation.
  94741. */
  94742. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  94743. if (!this._floorMeshesCollection) {
  94744. return;
  94745. }
  94746. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  94747. return;
  94748. }
  94749. this._floorMeshesCollection.push(floorMesh);
  94750. };
  94751. /**
  94752. * Removes a floor mesh from being used for teleportation.
  94753. * @param floorMesh the mesh to be removed.
  94754. */
  94755. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  94756. if (!this._floorMeshesCollection) {
  94757. return;
  94758. }
  94759. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  94760. if (meshIndex !== -1) {
  94761. this._floorMeshesCollection.splice(meshIndex, 1);
  94762. }
  94763. };
  94764. /**
  94765. * Enables interactions and teleportation using the VR controllers and gaze.
  94766. * @param vrTeleportationOptions options to modify teleportation behavior.
  94767. */
  94768. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  94769. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  94770. if (!this._teleportationInitialized) {
  94771. this._teleportationRequested = true;
  94772. this.enableInteractions();
  94773. if (vrTeleportationOptions.floorMeshName) {
  94774. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  94775. }
  94776. if (vrTeleportationOptions.floorMeshes) {
  94777. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  94778. }
  94779. if (this.leftController != null) {
  94780. this._enableTeleportationOnController(this.leftController);
  94781. }
  94782. if (this.rightController != null) {
  94783. this._enableTeleportationOnController(this.rightController);
  94784. }
  94785. // Creates an image processing post process for the vignette not relying
  94786. // on the main scene configuration for image processing to reduce setup and spaces
  94787. // (gamma/linear) conflicts.
  94788. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  94789. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  94790. imageProcessingConfiguration.vignetteEnabled = true;
  94791. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  94792. this._webVRCamera.detachPostProcess(this._postProcessMove);
  94793. this._teleportationInitialized = true;
  94794. if (this._isDefaultTeleportationTarget) {
  94795. this._createTeleportationCircles();
  94796. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  94797. }
  94798. }
  94799. };
  94800. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  94801. var _this = this;
  94802. var controllerMesh = controller.webVRController.mesh;
  94803. if (controllerMesh) {
  94804. controller._interactionsEnabled = true;
  94805. controller._activatePointer();
  94806. if (this.webVROptions.laserToggle) {
  94807. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  94808. // Enabling / disabling laserPointer
  94809. if (_this._displayLaserPointer && stateObject.value === 1) {
  94810. if (controller._activePointer) {
  94811. controller._deactivatePointer();
  94812. }
  94813. else {
  94814. controller._activatePointer();
  94815. }
  94816. if (_this.displayGaze) {
  94817. controller._gazeTracker.isVisible = controller._activePointer;
  94818. }
  94819. }
  94820. });
  94821. }
  94822. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  94823. var gazer = controller;
  94824. if (_this._noControllerIsActive) {
  94825. gazer = _this._cameraGazer;
  94826. }
  94827. if (!gazer._pointerDownOnMeshAsked) {
  94828. if (stateObject.value > _this._padSensibilityUp) {
  94829. gazer._selectionPointerDown();
  94830. }
  94831. }
  94832. else if (stateObject.value < _this._padSensibilityDown) {
  94833. gazer._selectionPointerUp();
  94834. }
  94835. });
  94836. }
  94837. };
  94838. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  94839. // Dont teleport if another gaze already requested teleportation
  94840. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  94841. return;
  94842. }
  94843. if (!gazer._teleportationRequestInitiated) {
  94844. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  94845. gazer._activatePointer();
  94846. gazer._teleportationRequestInitiated = true;
  94847. }
  94848. }
  94849. else {
  94850. // Listening to the proper controller values changes to confirm teleportation
  94851. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  94852. if (this._teleportActive) {
  94853. this._teleportCamera(this._haloCenter);
  94854. }
  94855. gazer._teleportationRequestInitiated = false;
  94856. }
  94857. }
  94858. };
  94859. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  94860. // Only rotate when user is not currently selecting a teleportation location
  94861. if (gazer._teleportationRequestInitiated) {
  94862. return;
  94863. }
  94864. if (!gazer._rotationLeftAsked) {
  94865. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  94866. gazer._rotationLeftAsked = true;
  94867. if (this._rotationAllowed) {
  94868. this._rotateCamera(false);
  94869. }
  94870. }
  94871. }
  94872. else {
  94873. if (stateObject.x > -this._padSensibilityDown) {
  94874. gazer._rotationLeftAsked = false;
  94875. }
  94876. }
  94877. if (!gazer._rotationRightAsked) {
  94878. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  94879. gazer._rotationRightAsked = true;
  94880. if (this._rotationAllowed) {
  94881. this._rotateCamera(true);
  94882. }
  94883. }
  94884. }
  94885. else {
  94886. if (stateObject.x < this._padSensibilityDown) {
  94887. gazer._rotationRightAsked = false;
  94888. }
  94889. }
  94890. };
  94891. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  94892. // Only teleport backwards when user is not currently selecting a teleportation location
  94893. if (gazer._teleportationRequestInitiated) {
  94894. return;
  94895. }
  94896. // Teleport backwards
  94897. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  94898. if (!gazer._teleportationBackRequestInitiated) {
  94899. if (!this.currentVRCamera) {
  94900. return;
  94901. }
  94902. // Get rotation and position of the current camera
  94903. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  94904. var position = this.currentVRCamera.position;
  94905. // If the camera has device position, use that instead
  94906. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  94907. rotation = this.currentVRCamera.deviceRotationQuaternion;
  94908. position = this.currentVRCamera.devicePosition;
  94909. }
  94910. // Get matrix with only the y rotation of the device rotation
  94911. rotation.toEulerAnglesToRef(this._workingVector);
  94912. this._workingVector.z = 0;
  94913. this._workingVector.x = 0;
  94914. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  94915. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  94916. // Rotate backwards ray by device rotation to cast at the ground behind the user
  94917. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  94918. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  94919. var ray = new BABYLON.Ray(position, this._workingVector);
  94920. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94921. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  94922. this._teleportCamera(hit.pickedPoint);
  94923. }
  94924. gazer._teleportationBackRequestInitiated = true;
  94925. }
  94926. }
  94927. else {
  94928. gazer._teleportationBackRequestInitiated = false;
  94929. }
  94930. };
  94931. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  94932. var _this = this;
  94933. var controllerMesh = controller.webVRController.mesh;
  94934. if (controllerMesh) {
  94935. if (!controller._interactionsEnabled) {
  94936. this._enableInteractionOnController(controller);
  94937. }
  94938. controller._interactionsEnabled = true;
  94939. controller._teleportationEnabled = true;
  94940. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94941. controller._dpadPressed = false;
  94942. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  94943. controller._dpadPressed = stateObject.pressed;
  94944. if (!controller._dpadPressed) {
  94945. controller._rotationLeftAsked = false;
  94946. controller._rotationRightAsked = false;
  94947. controller._teleportationBackRequestInitiated = false;
  94948. }
  94949. });
  94950. }
  94951. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  94952. if (_this.teleportationEnabled) {
  94953. _this._checkTeleportBackwards(stateObject, controller);
  94954. _this._checkTeleportWithRay(stateObject, controller);
  94955. }
  94956. _this._checkRotate(stateObject, controller);
  94957. });
  94958. }
  94959. };
  94960. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  94961. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  94962. this._teleportationTarget.isPickable = false;
  94963. var length = 512;
  94964. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  94965. dynamicTexture.hasAlpha = true;
  94966. var context = dynamicTexture.getContext();
  94967. var centerX = length / 2;
  94968. var centerY = length / 2;
  94969. var radius = 200;
  94970. context.beginPath();
  94971. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  94972. context.fillStyle = this._teleportationFillColor;
  94973. context.fill();
  94974. context.lineWidth = 10;
  94975. context.strokeStyle = this._teleportationBorderColor;
  94976. context.stroke();
  94977. context.closePath();
  94978. dynamicTexture.update();
  94979. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  94980. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  94981. this._teleportationTarget.material = teleportationCircleMaterial;
  94982. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  94983. torus.isPickable = false;
  94984. torus.parent = this._teleportationTarget;
  94985. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  94986. var keys = [];
  94987. keys.push({
  94988. frame: 0,
  94989. value: 0
  94990. });
  94991. keys.push({
  94992. frame: 30,
  94993. value: 0.4
  94994. });
  94995. keys.push({
  94996. frame: 60,
  94997. value: 0
  94998. });
  94999. animationInnerCircle.setKeys(keys);
  95000. var easingFunction = new BABYLON.SineEase();
  95001. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  95002. animationInnerCircle.setEasingFunction(easingFunction);
  95003. torus.animations = [];
  95004. torus.animations.push(animationInnerCircle);
  95005. this._scene.beginAnimation(torus, 0, 60, true);
  95006. this._hideTeleportationTarget();
  95007. };
  95008. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  95009. this._teleportActive = true;
  95010. if (this._teleportationInitialized) {
  95011. this._teleportationTarget.isVisible = true;
  95012. if (this._isDefaultTeleportationTarget) {
  95013. this._teleportationTarget.getChildren()[0].isVisible = true;
  95014. }
  95015. }
  95016. };
  95017. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  95018. this._teleportActive = false;
  95019. if (this._teleportationInitialized) {
  95020. this._teleportationTarget.isVisible = false;
  95021. if (this._isDefaultTeleportationTarget) {
  95022. this._teleportationTarget.getChildren()[0].isVisible = false;
  95023. }
  95024. }
  95025. };
  95026. VRExperienceHelper.prototype._rotateCamera = function (right) {
  95027. var _this = this;
  95028. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95029. return;
  95030. }
  95031. if (right) {
  95032. this._rotationAngle++;
  95033. }
  95034. else {
  95035. this._rotationAngle--;
  95036. }
  95037. this.currentVRCamera.animations = [];
  95038. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  95039. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95040. var animationRotationKeys = [];
  95041. animationRotationKeys.push({
  95042. frame: 0,
  95043. value: this.currentVRCamera.rotationQuaternion
  95044. });
  95045. animationRotationKeys.push({
  95046. frame: 6,
  95047. value: target
  95048. });
  95049. animationRotation.setKeys(animationRotationKeys);
  95050. animationRotation.setEasingFunction(this._circleEase);
  95051. this.currentVRCamera.animations.push(animationRotation);
  95052. this._postProcessMove.animations = [];
  95053. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95054. var vignetteWeightKeys = [];
  95055. vignetteWeightKeys.push({
  95056. frame: 0,
  95057. value: 0
  95058. });
  95059. vignetteWeightKeys.push({
  95060. frame: 3,
  95061. value: 4
  95062. });
  95063. vignetteWeightKeys.push({
  95064. frame: 6,
  95065. value: 0
  95066. });
  95067. animationPP.setKeys(vignetteWeightKeys);
  95068. animationPP.setEasingFunction(this._circleEase);
  95069. this._postProcessMove.animations.push(animationPP);
  95070. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95071. var vignetteStretchKeys = [];
  95072. vignetteStretchKeys.push({
  95073. frame: 0,
  95074. value: 0
  95075. });
  95076. vignetteStretchKeys.push({
  95077. frame: 3,
  95078. value: 10
  95079. });
  95080. vignetteStretchKeys.push({
  95081. frame: 6,
  95082. value: 0
  95083. });
  95084. animationPP2.setKeys(vignetteStretchKeys);
  95085. animationPP2.setEasingFunction(this._circleEase);
  95086. this._postProcessMove.animations.push(animationPP2);
  95087. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  95088. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  95089. this._postProcessMove.samples = 4;
  95090. this._webVRCamera.attachPostProcess(this._postProcessMove);
  95091. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  95092. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  95093. });
  95094. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  95095. };
  95096. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  95097. if (hit.pickedPoint) {
  95098. if (gazer._teleportationRequestInitiated) {
  95099. this._displayTeleportationTarget();
  95100. this._haloCenter.copyFrom(hit.pickedPoint);
  95101. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  95102. }
  95103. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  95104. if (pickNormal) {
  95105. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  95106. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  95107. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  95108. }
  95109. this._teleportationTarget.position.y += 0.1;
  95110. }
  95111. };
  95112. VRExperienceHelper.prototype._teleportCamera = function (location) {
  95113. var _this = this;
  95114. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95115. return;
  95116. }
  95117. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  95118. // offset of the headset from the anchor.
  95119. if (this.webVRCamera.leftCamera) {
  95120. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  95121. this._workingVector.subtractInPlace(this.webVRCamera.position);
  95122. location.subtractToRef(this._workingVector, this._workingVector);
  95123. }
  95124. else {
  95125. this._workingVector.copyFrom(location);
  95126. }
  95127. // Add height to account for user's height offset
  95128. if (this.isInVRMode) {
  95129. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  95130. }
  95131. else {
  95132. this._workingVector.y += this._defaultHeight;
  95133. }
  95134. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  95135. // Create animation from the camera's position to the new location
  95136. this.currentVRCamera.animations = [];
  95137. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95138. var animationCameraTeleportationKeys = [{
  95139. frame: 0,
  95140. value: this.currentVRCamera.position
  95141. },
  95142. {
  95143. frame: 11,
  95144. value: this._workingVector
  95145. }
  95146. ];
  95147. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  95148. animationCameraTeleportation.setEasingFunction(this._circleEase);
  95149. this.currentVRCamera.animations.push(animationCameraTeleportation);
  95150. this._postProcessMove.animations = [];
  95151. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95152. var vignetteWeightKeys = [];
  95153. vignetteWeightKeys.push({
  95154. frame: 0,
  95155. value: 0
  95156. });
  95157. vignetteWeightKeys.push({
  95158. frame: 5,
  95159. value: 8
  95160. });
  95161. vignetteWeightKeys.push({
  95162. frame: 11,
  95163. value: 0
  95164. });
  95165. animationPP.setKeys(vignetteWeightKeys);
  95166. this._postProcessMove.animations.push(animationPP);
  95167. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95168. var vignetteStretchKeys = [];
  95169. vignetteStretchKeys.push({
  95170. frame: 0,
  95171. value: 0
  95172. });
  95173. vignetteStretchKeys.push({
  95174. frame: 5,
  95175. value: 10
  95176. });
  95177. vignetteStretchKeys.push({
  95178. frame: 11,
  95179. value: 0
  95180. });
  95181. animationPP2.setKeys(vignetteStretchKeys);
  95182. this._postProcessMove.animations.push(animationPP2);
  95183. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  95184. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  95185. this._webVRCamera.attachPostProcess(this._postProcessMove);
  95186. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  95187. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  95188. });
  95189. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  95190. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  95191. });
  95192. this._hideTeleportationTarget();
  95193. };
  95194. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  95195. if (normal) {
  95196. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  95197. if (angle < Math.PI / 2) {
  95198. normal.scaleInPlace(-1);
  95199. }
  95200. }
  95201. return normal;
  95202. };
  95203. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  95204. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95205. return;
  95206. }
  95207. var ray = gazer._getForwardRay(this._rayLength);
  95208. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  95209. if (hit) {
  95210. // Populate the contrllers mesh that can be used for drag/drop
  95211. if (gazer._laserPointer) {
  95212. hit.originMesh = gazer._laserPointer.parent;
  95213. }
  95214. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  95215. }
  95216. gazer._currentHit = hit;
  95217. // Moving the gazeTracker on the mesh face targetted
  95218. if (hit && hit.pickedPoint) {
  95219. if (this._displayGaze) {
  95220. var multiplier = 1;
  95221. gazer._gazeTracker.isVisible = true;
  95222. if (gazer._isActionableMesh) {
  95223. multiplier = 3;
  95224. }
  95225. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  95226. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  95227. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  95228. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  95229. // To avoid z-fighting
  95230. var deltaFighting = 0.002;
  95231. if (pickNormal) {
  95232. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  95233. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  95234. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  95235. }
  95236. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  95237. if (gazer._gazeTracker.position.x < 0) {
  95238. gazer._gazeTracker.position.x += deltaFighting;
  95239. }
  95240. else {
  95241. gazer._gazeTracker.position.x -= deltaFighting;
  95242. }
  95243. if (gazer._gazeTracker.position.y < 0) {
  95244. gazer._gazeTracker.position.y += deltaFighting;
  95245. }
  95246. else {
  95247. gazer._gazeTracker.position.y -= deltaFighting;
  95248. }
  95249. if (gazer._gazeTracker.position.z < 0) {
  95250. gazer._gazeTracker.position.z += deltaFighting;
  95251. }
  95252. else {
  95253. gazer._gazeTracker.position.z -= deltaFighting;
  95254. }
  95255. }
  95256. // Changing the size of the laser pointer based on the distance from the targetted point
  95257. gazer._updatePointerDistance(hit.distance);
  95258. }
  95259. else {
  95260. gazer._updatePointerDistance();
  95261. gazer._gazeTracker.isVisible = false;
  95262. }
  95263. if (hit && hit.pickedMesh) {
  95264. // The object selected is the floor, we're in a teleportation scenario
  95265. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  95266. // Moving the teleportation area to this targetted point
  95267. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  95268. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  95269. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95270. }
  95271. gazer._currentMeshSelected = null;
  95272. if (gazer._teleportationRequestInitiated) {
  95273. this._moveTeleportationSelectorTo(hit, gazer, ray);
  95274. }
  95275. return;
  95276. }
  95277. // If not, we're in a selection scenario
  95278. //this._teleportationAllowed = false;
  95279. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  95280. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  95281. this.onNewMeshPicked.notifyObservers(hit);
  95282. gazer._currentMeshSelected = hit.pickedMesh;
  95283. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  95284. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  95285. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  95286. gazer._isActionableMesh = true;
  95287. }
  95288. else {
  95289. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95290. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95291. gazer._isActionableMesh = false;
  95292. }
  95293. try {
  95294. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  95295. }
  95296. catch (err) {
  95297. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  95298. }
  95299. }
  95300. else {
  95301. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95302. gazer._currentMeshSelected = null;
  95303. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95304. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95305. }
  95306. }
  95307. }
  95308. else {
  95309. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95310. gazer._currentMeshSelected = null;
  95311. //this._teleportationAllowed = false;
  95312. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95313. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95314. }
  95315. };
  95316. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  95317. if (mesh) {
  95318. this.onSelectedMeshUnselected.notifyObservers(mesh);
  95319. }
  95320. };
  95321. /**
  95322. * Sets the color of the laser ray from the vr controllers.
  95323. * @param color new color for the ray.
  95324. */
  95325. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  95326. if (this.leftController) {
  95327. this.leftController._setLaserPointerColor(color);
  95328. }
  95329. if (this.rightController) {
  95330. this.rightController._setLaserPointerColor(color);
  95331. }
  95332. };
  95333. /**
  95334. * Sets the color of the ray from the vr headsets gaze.
  95335. * @param color new color for the ray.
  95336. */
  95337. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  95338. if (!this._cameraGazer._gazeTracker.material) {
  95339. return;
  95340. }
  95341. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  95342. if (this.leftController) {
  95343. this.leftController._gazeTracker.material.emissiveColor = color;
  95344. }
  95345. if (this.rightController) {
  95346. this.rightController._gazeTracker.material.emissiveColor = color;
  95347. }
  95348. };
  95349. /**
  95350. * Exits VR and disposes of the vr experience helper
  95351. */
  95352. VRExperienceHelper.prototype.dispose = function () {
  95353. if (this.isInVRMode) {
  95354. this.exitVR();
  95355. }
  95356. if (this._postProcessMove) {
  95357. this._postProcessMove.dispose();
  95358. }
  95359. if (this._webVRCamera) {
  95360. this._webVRCamera.dispose();
  95361. }
  95362. if (this._vrDeviceOrientationCamera) {
  95363. this._vrDeviceOrientationCamera.dispose();
  95364. }
  95365. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  95366. document.body.removeChild(this._btnVR);
  95367. }
  95368. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  95369. this._deviceOrientationCamera.dispose();
  95370. }
  95371. if (this._cameraGazer) {
  95372. this._cameraGazer.dispose();
  95373. }
  95374. if (this.leftController) {
  95375. this.leftController.dispose();
  95376. }
  95377. if (this.rightController) {
  95378. this.rightController.dispose();
  95379. }
  95380. if (this._teleportationTarget) {
  95381. this._teleportationTarget.dispose();
  95382. }
  95383. this._floorMeshesCollection = [];
  95384. document.removeEventListener("keydown", this._onKeyDown);
  95385. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95386. window.removeEventListener("resize", this._onResize);
  95387. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  95388. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  95389. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  95390. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  95391. document.onmsfullscreenchange = null;
  95392. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  95393. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  95394. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  95395. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95396. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  95397. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  95398. this._scene.unregisterBeforeRender(this.beforeRender);
  95399. };
  95400. /**
  95401. * Gets the name of the VRExperienceHelper class
  95402. * @returns "VRExperienceHelper"
  95403. */
  95404. VRExperienceHelper.prototype.getClassName = function () {
  95405. return "VRExperienceHelper";
  95406. };
  95407. return VRExperienceHelper;
  95408. }());
  95409. BABYLON.VRExperienceHelper = VRExperienceHelper;
  95410. })(BABYLON || (BABYLON = {}));
  95411. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  95412. // Mainly based on these 2 articles :
  95413. // 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
  95414. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  95415. var BABYLON;
  95416. (function (BABYLON) {
  95417. /**
  95418. * Defines the potential axis of a Joystick
  95419. */
  95420. var JoystickAxis;
  95421. (function (JoystickAxis) {
  95422. /** X axis */
  95423. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  95424. /** Y axis */
  95425. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  95426. /** Z axis */
  95427. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  95428. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  95429. /**
  95430. * Class used to define virtual joystick (used in touch mode)
  95431. */
  95432. var VirtualJoystick = /** @class */ (function () {
  95433. /**
  95434. * Creates a new virtual joystick
  95435. * @param leftJoystick defines that the joystick is for left hand (false by default)
  95436. */
  95437. function VirtualJoystick(leftJoystick) {
  95438. var _this = this;
  95439. if (leftJoystick) {
  95440. this._leftJoystick = true;
  95441. }
  95442. else {
  95443. this._leftJoystick = false;
  95444. }
  95445. VirtualJoystick._globalJoystickIndex++;
  95446. // By default left & right arrow keys are moving the X
  95447. // and up & down keys are moving the Y
  95448. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95449. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95450. this.reverseLeftRight = false;
  95451. this.reverseUpDown = false;
  95452. // collections of pointers
  95453. this._touches = new BABYLON.StringDictionary();
  95454. this.deltaPosition = BABYLON.Vector3.Zero();
  95455. this._joystickSensibility = 25;
  95456. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  95457. this._onResize = function (evt) {
  95458. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  95459. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  95460. if (VirtualJoystick.vjCanvas) {
  95461. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  95462. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  95463. }
  95464. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  95465. };
  95466. // injecting a canvas element on top of the canvas 3D game
  95467. if (!VirtualJoystick.vjCanvas) {
  95468. window.addEventListener("resize", this._onResize, false);
  95469. VirtualJoystick.vjCanvas = document.createElement("canvas");
  95470. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  95471. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  95472. VirtualJoystick.vjCanvas.width = window.innerWidth;
  95473. VirtualJoystick.vjCanvas.height = window.innerHeight;
  95474. VirtualJoystick.vjCanvas.style.width = "100%";
  95475. VirtualJoystick.vjCanvas.style.height = "100%";
  95476. VirtualJoystick.vjCanvas.style.position = "absolute";
  95477. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  95478. VirtualJoystick.vjCanvas.style.top = "0px";
  95479. VirtualJoystick.vjCanvas.style.left = "0px";
  95480. VirtualJoystick.vjCanvas.style.zIndex = "5";
  95481. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  95482. // Support for jQuery PEP polyfill
  95483. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  95484. var context = VirtualJoystick.vjCanvas.getContext('2d');
  95485. if (!context) {
  95486. throw new Error("Unable to create canvas for virtual joystick");
  95487. }
  95488. VirtualJoystick.vjCanvasContext = context;
  95489. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  95490. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95491. document.body.appendChild(VirtualJoystick.vjCanvas);
  95492. }
  95493. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  95494. this.pressed = false;
  95495. // default joystick color
  95496. this._joystickColor = "cyan";
  95497. this._joystickPointerID = -1;
  95498. // current joystick position
  95499. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  95500. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  95501. // origin joystick position
  95502. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  95503. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  95504. this._onPointerDownHandlerRef = function (evt) {
  95505. _this._onPointerDown(evt);
  95506. };
  95507. this._onPointerMoveHandlerRef = function (evt) {
  95508. _this._onPointerMove(evt);
  95509. };
  95510. this._onPointerUpHandlerRef = function (evt) {
  95511. _this._onPointerUp(evt);
  95512. };
  95513. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  95514. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  95515. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  95516. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  95517. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  95518. evt.preventDefault(); // Disables system menu
  95519. }, false);
  95520. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95521. }
  95522. /**
  95523. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  95524. * @param newJoystickSensibility defines the new sensibility
  95525. */
  95526. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  95527. this._joystickSensibility = newJoystickSensibility;
  95528. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  95529. };
  95530. VirtualJoystick.prototype._onPointerDown = function (e) {
  95531. var positionOnScreenCondition;
  95532. e.preventDefault();
  95533. if (this._leftJoystick === true) {
  95534. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  95535. }
  95536. else {
  95537. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  95538. }
  95539. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  95540. // First contact will be dedicated to the virtual joystick
  95541. this._joystickPointerID = e.pointerId;
  95542. this._joystickPointerStartPos.x = e.clientX;
  95543. this._joystickPointerStartPos.y = e.clientY;
  95544. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  95545. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  95546. this._deltaJoystickVector.x = 0;
  95547. this._deltaJoystickVector.y = 0;
  95548. this.pressed = true;
  95549. this._touches.add(e.pointerId.toString(), e);
  95550. }
  95551. else {
  95552. // You can only trigger the action buttons with a joystick declared
  95553. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  95554. this._action();
  95555. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  95556. }
  95557. }
  95558. };
  95559. VirtualJoystick.prototype._onPointerMove = function (e) {
  95560. // If the current pointer is the one associated to the joystick (first touch contact)
  95561. if (this._joystickPointerID == e.pointerId) {
  95562. this._joystickPointerPos.x = e.clientX;
  95563. this._joystickPointerPos.y = e.clientY;
  95564. this._deltaJoystickVector = this._joystickPointerPos.clone();
  95565. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  95566. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  95567. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  95568. switch (this._axisTargetedByLeftAndRight) {
  95569. case JoystickAxis.X:
  95570. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  95571. break;
  95572. case JoystickAxis.Y:
  95573. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  95574. break;
  95575. case JoystickAxis.Z:
  95576. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  95577. break;
  95578. }
  95579. var directionUpDown = this.reverseUpDown ? 1 : -1;
  95580. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  95581. switch (this._axisTargetedByUpAndDown) {
  95582. case JoystickAxis.X:
  95583. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  95584. break;
  95585. case JoystickAxis.Y:
  95586. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  95587. break;
  95588. case JoystickAxis.Z:
  95589. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  95590. break;
  95591. }
  95592. }
  95593. else {
  95594. var data = this._touches.get(e.pointerId.toString());
  95595. if (data) {
  95596. data.x = e.clientX;
  95597. data.y = e.clientY;
  95598. }
  95599. }
  95600. };
  95601. VirtualJoystick.prototype._onPointerUp = function (e) {
  95602. if (this._joystickPointerID == e.pointerId) {
  95603. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  95604. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  95605. this._joystickPointerID = -1;
  95606. this.pressed = false;
  95607. }
  95608. else {
  95609. var touch = this._touches.get(e.pointerId.toString());
  95610. if (touch) {
  95611. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95612. }
  95613. }
  95614. this._deltaJoystickVector.x = 0;
  95615. this._deltaJoystickVector.y = 0;
  95616. this._touches.remove(e.pointerId.toString());
  95617. };
  95618. /**
  95619. * Change the color of the virtual joystick
  95620. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  95621. */
  95622. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  95623. this._joystickColor = newColor;
  95624. };
  95625. /**
  95626. * Defines a callback to call when the joystick is touched
  95627. * @param action defines the callback
  95628. */
  95629. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  95630. this._action = action;
  95631. };
  95632. /**
  95633. * Defines which axis you'd like to control for left & right
  95634. * @param axis defines the axis to use
  95635. */
  95636. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  95637. switch (axis) {
  95638. case JoystickAxis.X:
  95639. case JoystickAxis.Y:
  95640. case JoystickAxis.Z:
  95641. this._axisTargetedByLeftAndRight = axis;
  95642. break;
  95643. default:
  95644. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95645. break;
  95646. }
  95647. };
  95648. /**
  95649. * Defines which axis you'd like to control for up & down
  95650. * @param axis defines the axis to use
  95651. */
  95652. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  95653. switch (axis) {
  95654. case JoystickAxis.X:
  95655. case JoystickAxis.Y:
  95656. case JoystickAxis.Z:
  95657. this._axisTargetedByUpAndDown = axis;
  95658. break;
  95659. default:
  95660. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95661. break;
  95662. }
  95663. };
  95664. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  95665. var _this = this;
  95666. if (this.pressed) {
  95667. this._touches.forEach(function (key, touch) {
  95668. if (touch.pointerId === _this._joystickPointerID) {
  95669. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  95670. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  95671. VirtualJoystick.vjCanvasContext.beginPath();
  95672. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95673. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95674. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  95675. VirtualJoystick.vjCanvasContext.stroke();
  95676. VirtualJoystick.vjCanvasContext.closePath();
  95677. VirtualJoystick.vjCanvasContext.beginPath();
  95678. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95679. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95680. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  95681. VirtualJoystick.vjCanvasContext.stroke();
  95682. VirtualJoystick.vjCanvasContext.closePath();
  95683. VirtualJoystick.vjCanvasContext.beginPath();
  95684. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95685. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  95686. VirtualJoystick.vjCanvasContext.stroke();
  95687. VirtualJoystick.vjCanvasContext.closePath();
  95688. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  95689. }
  95690. else {
  95691. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95692. VirtualJoystick.vjCanvasContext.beginPath();
  95693. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  95694. VirtualJoystick.vjCanvasContext.beginPath();
  95695. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  95696. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95697. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  95698. VirtualJoystick.vjCanvasContext.stroke();
  95699. VirtualJoystick.vjCanvasContext.closePath();
  95700. touch.prevX = touch.x;
  95701. touch.prevY = touch.y;
  95702. }
  95703. ;
  95704. });
  95705. }
  95706. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95707. };
  95708. /**
  95709. * Release internal HTML canvas
  95710. */
  95711. VirtualJoystick.prototype.releaseCanvas = function () {
  95712. if (VirtualJoystick.vjCanvas) {
  95713. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  95714. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  95715. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  95716. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  95717. window.removeEventListener("resize", this._onResize);
  95718. document.body.removeChild(VirtualJoystick.vjCanvas);
  95719. VirtualJoystick.vjCanvas = null;
  95720. }
  95721. };
  95722. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  95723. VirtualJoystick._globalJoystickIndex = 0;
  95724. return VirtualJoystick;
  95725. }());
  95726. BABYLON.VirtualJoystick = VirtualJoystick;
  95727. })(BABYLON || (BABYLON = {}));
  95728. //# sourceMappingURL=babylon.virtualJoystick.js.map
  95729. var BABYLON;
  95730. (function (BABYLON) {
  95731. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  95732. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  95733. });
  95734. // We're mainly based on the logic defined into the FreeCamera code
  95735. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  95736. __extends(VirtualJoysticksCamera, _super);
  95737. function VirtualJoysticksCamera(name, position, scene) {
  95738. var _this = _super.call(this, name, position, scene) || this;
  95739. _this.inputs.addVirtualJoystick();
  95740. return _this;
  95741. }
  95742. VirtualJoysticksCamera.prototype.getClassName = function () {
  95743. return "VirtualJoysticksCamera";
  95744. };
  95745. return VirtualJoysticksCamera;
  95746. }(BABYLON.FreeCamera));
  95747. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  95748. })(BABYLON || (BABYLON = {}));
  95749. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  95750. var BABYLON;
  95751. (function (BABYLON) {
  95752. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  95753. function FreeCameraVirtualJoystickInput() {
  95754. }
  95755. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  95756. return this._leftjoystick;
  95757. };
  95758. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  95759. return this._rightjoystick;
  95760. };
  95761. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  95762. if (this._leftjoystick) {
  95763. var camera = this.camera;
  95764. var speed = camera._computeLocalCameraSpeed() * 50;
  95765. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  95766. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  95767. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  95768. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  95769. if (!this._leftjoystick.pressed) {
  95770. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  95771. }
  95772. if (!this._rightjoystick.pressed) {
  95773. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  95774. }
  95775. }
  95776. };
  95777. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  95778. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  95779. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  95780. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  95781. this._leftjoystick.setJoystickSensibility(0.15);
  95782. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  95783. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  95784. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  95785. this._rightjoystick.reverseUpDown = true;
  95786. this._rightjoystick.setJoystickSensibility(0.05);
  95787. this._rightjoystick.setJoystickColor("yellow");
  95788. };
  95789. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  95790. this._leftjoystick.releaseCanvas();
  95791. this._rightjoystick.releaseCanvas();
  95792. };
  95793. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  95794. return "FreeCameraVirtualJoystickInput";
  95795. };
  95796. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  95797. return "virtualJoystick";
  95798. };
  95799. return FreeCameraVirtualJoystickInput;
  95800. }());
  95801. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  95802. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  95803. })(BABYLON || (BABYLON = {}));
  95804. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  95805. var BABYLON;
  95806. (function (BABYLON) {
  95807. var SimplificationSettings = /** @class */ (function () {
  95808. function SimplificationSettings(quality, distance, optimizeMesh) {
  95809. this.quality = quality;
  95810. this.distance = distance;
  95811. this.optimizeMesh = optimizeMesh;
  95812. }
  95813. return SimplificationSettings;
  95814. }());
  95815. BABYLON.SimplificationSettings = SimplificationSettings;
  95816. var SimplificationQueue = /** @class */ (function () {
  95817. function SimplificationQueue() {
  95818. this.running = false;
  95819. this._simplificationArray = [];
  95820. }
  95821. SimplificationQueue.prototype.addTask = function (task) {
  95822. this._simplificationArray.push(task);
  95823. };
  95824. SimplificationQueue.prototype.executeNext = function () {
  95825. var task = this._simplificationArray.pop();
  95826. if (task) {
  95827. this.running = true;
  95828. this.runSimplification(task);
  95829. }
  95830. else {
  95831. this.running = false;
  95832. }
  95833. };
  95834. SimplificationQueue.prototype.runSimplification = function (task) {
  95835. var _this = this;
  95836. if (task.parallelProcessing) {
  95837. //parallel simplifier
  95838. task.settings.forEach(function (setting) {
  95839. var simplifier = _this.getSimplifier(task);
  95840. simplifier.simplify(setting, function (newMesh) {
  95841. task.mesh.addLODLevel(setting.distance, newMesh);
  95842. newMesh.isVisible = true;
  95843. //check if it is the last
  95844. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  95845. //all done, run the success callback.
  95846. task.successCallback();
  95847. }
  95848. _this.executeNext();
  95849. });
  95850. });
  95851. }
  95852. else {
  95853. //single simplifier.
  95854. var simplifier = this.getSimplifier(task);
  95855. var runDecimation = function (setting, callback) {
  95856. simplifier.simplify(setting, function (newMesh) {
  95857. task.mesh.addLODLevel(setting.distance, newMesh);
  95858. newMesh.isVisible = true;
  95859. //run the next quality level
  95860. callback();
  95861. });
  95862. };
  95863. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  95864. runDecimation(task.settings[loop.index], function () {
  95865. loop.executeNext();
  95866. });
  95867. }, function () {
  95868. //execution ended, run the success callback.
  95869. if (task.successCallback) {
  95870. task.successCallback();
  95871. }
  95872. _this.executeNext();
  95873. });
  95874. }
  95875. };
  95876. SimplificationQueue.prototype.getSimplifier = function (task) {
  95877. switch (task.simplificationType) {
  95878. case SimplificationType.QUADRATIC:
  95879. default:
  95880. return new QuadraticErrorSimplification(task.mesh);
  95881. }
  95882. };
  95883. return SimplificationQueue;
  95884. }());
  95885. BABYLON.SimplificationQueue = SimplificationQueue;
  95886. /**
  95887. * The implemented types of simplification
  95888. * At the moment only Quadratic Error Decimation is implemented
  95889. */
  95890. var SimplificationType;
  95891. (function (SimplificationType) {
  95892. /** Quadratic error decimation */
  95893. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  95894. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  95895. var DecimationTriangle = /** @class */ (function () {
  95896. function DecimationTriangle(vertices) {
  95897. this.vertices = vertices;
  95898. this.error = new Array(4);
  95899. this.deleted = false;
  95900. this.isDirty = false;
  95901. this.deletePending = false;
  95902. this.borderFactor = 0;
  95903. }
  95904. return DecimationTriangle;
  95905. }());
  95906. BABYLON.DecimationTriangle = DecimationTriangle;
  95907. var DecimationVertex = /** @class */ (function () {
  95908. function DecimationVertex(position, id) {
  95909. this.position = position;
  95910. this.id = id;
  95911. this.isBorder = true;
  95912. this.q = new QuadraticMatrix();
  95913. this.triangleCount = 0;
  95914. this.triangleStart = 0;
  95915. this.originalOffsets = [];
  95916. }
  95917. DecimationVertex.prototype.updatePosition = function (newPosition) {
  95918. this.position.copyFrom(newPosition);
  95919. };
  95920. return DecimationVertex;
  95921. }());
  95922. BABYLON.DecimationVertex = DecimationVertex;
  95923. var QuadraticMatrix = /** @class */ (function () {
  95924. function QuadraticMatrix(data) {
  95925. this.data = new Array(10);
  95926. for (var i = 0; i < 10; ++i) {
  95927. if (data && data[i]) {
  95928. this.data[i] = data[i];
  95929. }
  95930. else {
  95931. this.data[i] = 0;
  95932. }
  95933. }
  95934. }
  95935. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  95936. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  95937. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  95938. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  95939. return det;
  95940. };
  95941. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  95942. for (var i = 0; i < 10; ++i) {
  95943. this.data[i] += matrix.data[i];
  95944. }
  95945. };
  95946. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  95947. for (var i = 0; i < 10; ++i) {
  95948. this.data[i] += data[i];
  95949. }
  95950. };
  95951. QuadraticMatrix.prototype.add = function (matrix) {
  95952. var m = new QuadraticMatrix();
  95953. for (var i = 0; i < 10; ++i) {
  95954. m.data[i] = this.data[i] + matrix.data[i];
  95955. }
  95956. return m;
  95957. };
  95958. QuadraticMatrix.FromData = function (a, b, c, d) {
  95959. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  95960. };
  95961. //returning an array to avoid garbage collection
  95962. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  95963. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  95964. };
  95965. return QuadraticMatrix;
  95966. }());
  95967. BABYLON.QuadraticMatrix = QuadraticMatrix;
  95968. var Reference = /** @class */ (function () {
  95969. function Reference(vertexId, triangleId) {
  95970. this.vertexId = vertexId;
  95971. this.triangleId = triangleId;
  95972. }
  95973. return Reference;
  95974. }());
  95975. BABYLON.Reference = Reference;
  95976. /**
  95977. * An implementation of the Quadratic Error simplification algorithm.
  95978. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  95979. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  95980. * @author RaananW
  95981. */
  95982. var QuadraticErrorSimplification = /** @class */ (function () {
  95983. function QuadraticErrorSimplification(_mesh) {
  95984. this._mesh = _mesh;
  95985. this.syncIterations = 5000;
  95986. this.aggressiveness = 7;
  95987. this.decimationIterations = 100;
  95988. this.boundingBoxEpsilon = BABYLON.Epsilon;
  95989. }
  95990. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  95991. var _this = this;
  95992. this.initDecimatedMesh();
  95993. //iterating through the submeshes array, one after the other.
  95994. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  95995. _this.initWithMesh(loop.index, function () {
  95996. _this.runDecimation(settings, loop.index, function () {
  95997. loop.executeNext();
  95998. });
  95999. }, settings.optimizeMesh);
  96000. }, function () {
  96001. setTimeout(function () {
  96002. successCallback(_this._reconstructedMesh);
  96003. }, 0);
  96004. });
  96005. };
  96006. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  96007. var _this = this;
  96008. var targetCount = ~~(this.triangles.length * settings.quality);
  96009. var deletedTriangles = 0;
  96010. var triangleCount = this.triangles.length;
  96011. var iterationFunction = function (iteration, callback) {
  96012. setTimeout(function () {
  96013. if (iteration % 5 === 0) {
  96014. _this.updateMesh(iteration === 0);
  96015. }
  96016. for (var i = 0; i < _this.triangles.length; ++i) {
  96017. _this.triangles[i].isDirty = false;
  96018. }
  96019. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  96020. var trianglesIterator = function (i) {
  96021. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  96022. var t = _this.triangles[tIdx];
  96023. if (!t)
  96024. return;
  96025. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  96026. return;
  96027. }
  96028. for (var j = 0; j < 3; ++j) {
  96029. if (t.error[j] < threshold) {
  96030. var deleted0 = [];
  96031. var deleted1 = [];
  96032. var v0 = t.vertices[j];
  96033. var v1 = t.vertices[(j + 1) % 3];
  96034. if (v0.isBorder || v1.isBorder)
  96035. continue;
  96036. var p = BABYLON.Vector3.Zero();
  96037. var n = BABYLON.Vector3.Zero();
  96038. var uv = BABYLON.Vector2.Zero();
  96039. var color = new BABYLON.Color4(0, 0, 0, 1);
  96040. _this.calculateError(v0, v1, p, n, uv, color);
  96041. var delTr = new Array();
  96042. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  96043. continue;
  96044. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  96045. continue;
  96046. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  96047. continue;
  96048. var uniqueArray = new Array();
  96049. delTr.forEach(function (deletedT) {
  96050. if (uniqueArray.indexOf(deletedT) === -1) {
  96051. deletedT.deletePending = true;
  96052. uniqueArray.push(deletedT);
  96053. }
  96054. });
  96055. if (uniqueArray.length % 2 !== 0) {
  96056. continue;
  96057. }
  96058. v0.q = v1.q.add(v0.q);
  96059. v0.updatePosition(p);
  96060. var tStart = _this.references.length;
  96061. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  96062. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  96063. var tCount = _this.references.length - tStart;
  96064. if (tCount <= v0.triangleCount) {
  96065. if (tCount) {
  96066. for (var c = 0; c < tCount; c++) {
  96067. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  96068. }
  96069. }
  96070. }
  96071. else {
  96072. v0.triangleStart = tStart;
  96073. }
  96074. v0.triangleCount = tCount;
  96075. break;
  96076. }
  96077. }
  96078. };
  96079. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  96080. }, 0);
  96081. };
  96082. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  96083. if (triangleCount - deletedTriangles <= targetCount)
  96084. loop.breakLoop();
  96085. else {
  96086. iterationFunction(loop.index, function () {
  96087. loop.executeNext();
  96088. });
  96089. }
  96090. }, function () {
  96091. setTimeout(function () {
  96092. //reconstruct this part of the mesh
  96093. _this.reconstructMesh(submeshIndex);
  96094. successCallback();
  96095. }, 0);
  96096. });
  96097. };
  96098. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  96099. var _this = this;
  96100. this.vertices = [];
  96101. this.triangles = [];
  96102. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96103. var indices = this._mesh.getIndices();
  96104. var submesh = this._mesh.subMeshes[submeshIndex];
  96105. var findInVertices = function (positionToSearch) {
  96106. if (optimizeMesh) {
  96107. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  96108. if (_this.vertices[ii].position.equals(positionToSearch)) {
  96109. return _this.vertices[ii];
  96110. }
  96111. }
  96112. }
  96113. return null;
  96114. };
  96115. var vertexReferences = [];
  96116. var vertexInit = function (i) {
  96117. if (!positionData) {
  96118. return;
  96119. }
  96120. var offset = i + submesh.verticesStart;
  96121. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  96122. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  96123. vertex.originalOffsets.push(offset);
  96124. if (vertex.id === _this.vertices.length) {
  96125. _this.vertices.push(vertex);
  96126. }
  96127. vertexReferences.push(vertex.id);
  96128. };
  96129. //var totalVertices = mesh.getTotalVertices();
  96130. var totalVertices = submesh.verticesCount;
  96131. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  96132. var indicesInit = function (i) {
  96133. if (!indices) {
  96134. return;
  96135. }
  96136. var offset = (submesh.indexStart / 3) + i;
  96137. var pos = (offset * 3);
  96138. var i0 = indices[pos + 0];
  96139. var i1 = indices[pos + 1];
  96140. var i2 = indices[pos + 2];
  96141. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  96142. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  96143. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  96144. var triangle = new DecimationTriangle([v0, v1, v2]);
  96145. triangle.originalOffset = pos;
  96146. _this.triangles.push(triangle);
  96147. };
  96148. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  96149. _this.init(callback);
  96150. });
  96151. });
  96152. };
  96153. QuadraticErrorSimplification.prototype.init = function (callback) {
  96154. var _this = this;
  96155. var triangleInit1 = function (i) {
  96156. var t = _this.triangles[i];
  96157. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  96158. for (var j = 0; j < 3; j++) {
  96159. 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))));
  96160. }
  96161. };
  96162. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  96163. var triangleInit2 = function (i) {
  96164. var t = _this.triangles[i];
  96165. for (var j = 0; j < 3; ++j) {
  96166. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  96167. }
  96168. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  96169. };
  96170. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  96171. callback();
  96172. });
  96173. });
  96174. };
  96175. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  96176. var newTriangles = [];
  96177. var i;
  96178. for (i = 0; i < this.vertices.length; ++i) {
  96179. this.vertices[i].triangleCount = 0;
  96180. }
  96181. var t;
  96182. var j;
  96183. for (i = 0; i < this.triangles.length; ++i) {
  96184. if (!this.triangles[i].deleted) {
  96185. t = this.triangles[i];
  96186. for (j = 0; j < 3; ++j) {
  96187. t.vertices[j].triangleCount = 1;
  96188. }
  96189. newTriangles.push(t);
  96190. }
  96191. }
  96192. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  96193. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  96194. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  96195. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  96196. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  96197. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  96198. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  96199. var vertexCount = 0;
  96200. for (i = 0; i < this.vertices.length; ++i) {
  96201. var vertex = this.vertices[i];
  96202. vertex.id = vertexCount;
  96203. if (vertex.triangleCount) {
  96204. vertex.originalOffsets.forEach(function (originalOffset) {
  96205. if (!normalData) {
  96206. return;
  96207. }
  96208. newPositionData.push(vertex.position.x);
  96209. newPositionData.push(vertex.position.y);
  96210. newPositionData.push(vertex.position.z);
  96211. newNormalData.push(normalData[originalOffset * 3]);
  96212. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  96213. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  96214. if (uvs && uvs.length) {
  96215. newUVsData.push(uvs[(originalOffset * 2)]);
  96216. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  96217. }
  96218. else if (colorsData && colorsData.length) {
  96219. newColorsData.push(colorsData[(originalOffset * 4)]);
  96220. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  96221. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  96222. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  96223. }
  96224. ++vertexCount;
  96225. });
  96226. }
  96227. }
  96228. var startingIndex = this._reconstructedMesh.getTotalIndices();
  96229. var startingVertex = this._reconstructedMesh.getTotalVertices();
  96230. var submeshesArray = this._reconstructedMesh.subMeshes;
  96231. this._reconstructedMesh.subMeshes = [];
  96232. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  96233. var originalIndices = this._mesh.getIndices();
  96234. for (i = 0; i < newTriangles.length; ++i) {
  96235. t = newTriangles[i]; //now get the new referencing point for each vertex
  96236. [0, 1, 2].forEach(function (idx) {
  96237. var id = originalIndices[t.originalOffset + idx];
  96238. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  96239. if (offset < 0)
  96240. offset = 0;
  96241. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  96242. });
  96243. }
  96244. //overwriting the old vertex buffers and indices.
  96245. this._reconstructedMesh.setIndices(newIndicesArray);
  96246. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  96247. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  96248. if (newUVsData.length > 0)
  96249. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  96250. if (newColorsData.length > 0)
  96251. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  96252. //create submesh
  96253. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  96254. if (submeshIndex > 0) {
  96255. this._reconstructedMesh.subMeshes = [];
  96256. submeshesArray.forEach(function (submesh) {
  96257. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  96258. });
  96259. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  96260. }
  96261. };
  96262. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  96263. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  96264. this._reconstructedMesh.material = this._mesh.material;
  96265. this._reconstructedMesh.parent = this._mesh.parent;
  96266. this._reconstructedMesh.isVisible = false;
  96267. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  96268. };
  96269. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  96270. for (var i = 0; i < vertex1.triangleCount; ++i) {
  96271. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  96272. if (t.deleted)
  96273. continue;
  96274. var s = this.references[vertex1.triangleStart + i].vertexId;
  96275. var v1 = t.vertices[(s + 1) % 3];
  96276. var v2 = t.vertices[(s + 2) % 3];
  96277. if ((v1 === vertex2 || v2 === vertex2)) {
  96278. deletedArray[i] = true;
  96279. delTr.push(t);
  96280. continue;
  96281. }
  96282. var d1 = v1.position.subtract(point);
  96283. d1 = d1.normalize();
  96284. var d2 = v2.position.subtract(point);
  96285. d2 = d2.normalize();
  96286. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  96287. return true;
  96288. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  96289. deletedArray[i] = false;
  96290. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  96291. return true;
  96292. }
  96293. return false;
  96294. };
  96295. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  96296. var newDeleted = deletedTriangles;
  96297. for (var i = 0; i < vertex.triangleCount; ++i) {
  96298. var ref = this.references[vertex.triangleStart + i];
  96299. var t = this.triangles[ref.triangleId];
  96300. if (t.deleted)
  96301. continue;
  96302. if (deletedArray[i] && t.deletePending) {
  96303. t.deleted = true;
  96304. newDeleted++;
  96305. continue;
  96306. }
  96307. t.vertices[ref.vertexId] = origVertex;
  96308. t.isDirty = true;
  96309. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  96310. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  96311. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  96312. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  96313. this.references.push(ref);
  96314. }
  96315. return newDeleted;
  96316. };
  96317. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  96318. for (var i = 0; i < this.vertices.length; ++i) {
  96319. var vCount = [];
  96320. var vId = [];
  96321. var v = this.vertices[i];
  96322. var j;
  96323. for (j = 0; j < v.triangleCount; ++j) {
  96324. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  96325. for (var ii = 0; ii < 3; ii++) {
  96326. var ofs = 0;
  96327. var vv = triangle.vertices[ii];
  96328. while (ofs < vCount.length) {
  96329. if (vId[ofs] === vv.id)
  96330. break;
  96331. ++ofs;
  96332. }
  96333. if (ofs === vCount.length) {
  96334. vCount.push(1);
  96335. vId.push(vv.id);
  96336. }
  96337. else {
  96338. vCount[ofs]++;
  96339. }
  96340. }
  96341. }
  96342. for (j = 0; j < vCount.length; ++j) {
  96343. if (vCount[j] === 1) {
  96344. this.vertices[vId[j]].isBorder = true;
  96345. }
  96346. else {
  96347. this.vertices[vId[j]].isBorder = false;
  96348. }
  96349. }
  96350. }
  96351. };
  96352. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  96353. if (identifyBorders === void 0) { identifyBorders = false; }
  96354. var i;
  96355. if (!identifyBorders) {
  96356. var newTrianglesVector = [];
  96357. for (i = 0; i < this.triangles.length; ++i) {
  96358. if (!this.triangles[i].deleted) {
  96359. newTrianglesVector.push(this.triangles[i]);
  96360. }
  96361. }
  96362. this.triangles = newTrianglesVector;
  96363. }
  96364. for (i = 0; i < this.vertices.length; ++i) {
  96365. this.vertices[i].triangleCount = 0;
  96366. this.vertices[i].triangleStart = 0;
  96367. }
  96368. var t;
  96369. var j;
  96370. var v;
  96371. for (i = 0; i < this.triangles.length; ++i) {
  96372. t = this.triangles[i];
  96373. for (j = 0; j < 3; ++j) {
  96374. v = t.vertices[j];
  96375. v.triangleCount++;
  96376. }
  96377. }
  96378. var tStart = 0;
  96379. for (i = 0; i < this.vertices.length; ++i) {
  96380. this.vertices[i].triangleStart = tStart;
  96381. tStart += this.vertices[i].triangleCount;
  96382. this.vertices[i].triangleCount = 0;
  96383. }
  96384. var newReferences = new Array(this.triangles.length * 3);
  96385. for (i = 0; i < this.triangles.length; ++i) {
  96386. t = this.triangles[i];
  96387. for (j = 0; j < 3; ++j) {
  96388. v = t.vertices[j];
  96389. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  96390. v.triangleCount++;
  96391. }
  96392. }
  96393. this.references = newReferences;
  96394. if (identifyBorders) {
  96395. this.identifyBorder();
  96396. }
  96397. };
  96398. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  96399. var x = point.x;
  96400. var y = point.y;
  96401. var z = point.z;
  96402. 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
  96403. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  96404. };
  96405. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  96406. var q = vertex1.q.add(vertex2.q);
  96407. var border = vertex1.isBorder && vertex2.isBorder;
  96408. var error = 0;
  96409. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  96410. if (qDet !== 0 && !border) {
  96411. if (!pointResult) {
  96412. pointResult = BABYLON.Vector3.Zero();
  96413. }
  96414. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  96415. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  96416. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  96417. error = this.vertexError(q, pointResult);
  96418. }
  96419. else {
  96420. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  96421. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  96422. var error1 = this.vertexError(q, vertex1.position);
  96423. var error2 = this.vertexError(q, vertex2.position);
  96424. var error3 = this.vertexError(q, p3);
  96425. error = Math.min(error1, error2, error3);
  96426. if (error === error1) {
  96427. if (pointResult) {
  96428. pointResult.copyFrom(vertex1.position);
  96429. }
  96430. }
  96431. else if (error === error2) {
  96432. if (pointResult) {
  96433. pointResult.copyFrom(vertex2.position);
  96434. }
  96435. }
  96436. else {
  96437. if (pointResult) {
  96438. pointResult.copyFrom(p3);
  96439. }
  96440. }
  96441. }
  96442. return error;
  96443. };
  96444. return QuadraticErrorSimplification;
  96445. }());
  96446. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  96447. })(BABYLON || (BABYLON = {}));
  96448. //# sourceMappingURL=babylon.meshSimplification.js.map
  96449. var BABYLON;
  96450. (function (BABYLON) {
  96451. var MeshLODLevel = /** @class */ (function () {
  96452. function MeshLODLevel(distance, mesh) {
  96453. this.distance = distance;
  96454. this.mesh = mesh;
  96455. }
  96456. return MeshLODLevel;
  96457. }());
  96458. BABYLON.MeshLODLevel = MeshLODLevel;
  96459. })(BABYLON || (BABYLON = {}));
  96460. //# sourceMappingURL=babylon.meshLODLevel.js.map
  96461. var BABYLON;
  96462. (function (BABYLON) {
  96463. /**
  96464. * Defines the root class used to create scene optimization to use with SceneOptimizer
  96465. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96466. */
  96467. var SceneOptimization = /** @class */ (function () {
  96468. /**
  96469. * Creates the SceneOptimization object
  96470. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96471. * @param desc defines the description associated with the optimization
  96472. */
  96473. function SceneOptimization(
  96474. /**
  96475. * Defines the priority of this optimization (0 by default which means first in the list)
  96476. */
  96477. priority) {
  96478. if (priority === void 0) { priority = 0; }
  96479. this.priority = priority;
  96480. }
  96481. /**
  96482. * Gets a string describing the action executed by the current optimization
  96483. * @returns description string
  96484. */
  96485. SceneOptimization.prototype.getDescription = function () {
  96486. return "";
  96487. };
  96488. /**
  96489. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96490. * @param scene defines the current scene where to apply this optimization
  96491. * @param optimizer defines the current optimizer
  96492. * @returns true if everything that can be done was applied
  96493. */
  96494. SceneOptimization.prototype.apply = function (scene, optimizer) {
  96495. return true;
  96496. };
  96497. ;
  96498. return SceneOptimization;
  96499. }());
  96500. BABYLON.SceneOptimization = SceneOptimization;
  96501. /**
  96502. * Defines an optimization used to reduce the size of render target textures
  96503. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96504. */
  96505. var TextureOptimization = /** @class */ (function (_super) {
  96506. __extends(TextureOptimization, _super);
  96507. /**
  96508. * Creates the TextureOptimization object
  96509. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96510. * @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
  96511. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  96512. */
  96513. function TextureOptimization(
  96514. /**
  96515. * Defines the priority of this optimization (0 by default which means first in the list)
  96516. */
  96517. priority,
  96518. /**
  96519. * 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
  96520. */
  96521. maximumSize,
  96522. /**
  96523. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  96524. */
  96525. step) {
  96526. if (priority === void 0) { priority = 0; }
  96527. if (maximumSize === void 0) { maximumSize = 1024; }
  96528. if (step === void 0) { step = 0.5; }
  96529. var _this = _super.call(this, priority) || this;
  96530. _this.priority = priority;
  96531. _this.maximumSize = maximumSize;
  96532. _this.step = step;
  96533. return _this;
  96534. }
  96535. /**
  96536. * Gets a string describing the action executed by the current optimization
  96537. * @returns description string
  96538. */
  96539. TextureOptimization.prototype.getDescription = function () {
  96540. return "Reducing render target texture size to " + this.maximumSize;
  96541. };
  96542. /**
  96543. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96544. * @param scene defines the current scene where to apply this optimization
  96545. * @param optimizer defines the current optimizer
  96546. * @returns true if everything that can be done was applied
  96547. */
  96548. TextureOptimization.prototype.apply = function (scene, optimizer) {
  96549. var allDone = true;
  96550. for (var index = 0; index < scene.textures.length; index++) {
  96551. var texture = scene.textures[index];
  96552. if (!texture.canRescale || texture.getContext) {
  96553. continue;
  96554. }
  96555. var currentSize = texture.getSize();
  96556. var maxDimension = Math.max(currentSize.width, currentSize.height);
  96557. if (maxDimension > this.maximumSize) {
  96558. texture.scale(this.step);
  96559. allDone = false;
  96560. }
  96561. }
  96562. return allDone;
  96563. };
  96564. return TextureOptimization;
  96565. }(SceneOptimization));
  96566. BABYLON.TextureOptimization = TextureOptimization;
  96567. /**
  96568. * Defines an optimization used to increase or decrease the rendering resolution
  96569. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96570. */
  96571. var HardwareScalingOptimization = /** @class */ (function (_super) {
  96572. __extends(HardwareScalingOptimization, _super);
  96573. /**
  96574. * Creates the HardwareScalingOptimization object
  96575. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96576. * @param maximumScale defines the maximum scale to use (2 by default)
  96577. * @param step defines the step to use between two passes (0.5 by default)
  96578. */
  96579. function HardwareScalingOptimization(
  96580. /**
  96581. * Defines the priority of this optimization (0 by default which means first in the list)
  96582. */
  96583. priority,
  96584. /**
  96585. * Defines the maximum scale to use (2 by default)
  96586. */
  96587. maximumScale,
  96588. /**
  96589. * Defines the step to use between two passes (0.5 by default)
  96590. */
  96591. step) {
  96592. if (priority === void 0) { priority = 0; }
  96593. if (maximumScale === void 0) { maximumScale = 2; }
  96594. if (step === void 0) { step = 0.25; }
  96595. var _this = _super.call(this, priority) || this;
  96596. _this.priority = priority;
  96597. _this.maximumScale = maximumScale;
  96598. _this.step = step;
  96599. _this._currentScale = -1;
  96600. _this._directionOffset = 1;
  96601. return _this;
  96602. }
  96603. /**
  96604. * Gets a string describing the action executed by the current optimization
  96605. * @return description string
  96606. */
  96607. HardwareScalingOptimization.prototype.getDescription = function () {
  96608. return "Setting hardware scaling level to " + this._currentScale;
  96609. };
  96610. /**
  96611. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96612. * @param scene defines the current scene where to apply this optimization
  96613. * @param optimizer defines the current optimizer
  96614. * @returns true if everything that can be done was applied
  96615. */
  96616. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  96617. if (this._currentScale === -1) {
  96618. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  96619. if (this._currentScale > this.maximumScale) {
  96620. this._directionOffset = -1;
  96621. }
  96622. }
  96623. this._currentScale += this._directionOffset * this.step;
  96624. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  96625. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  96626. };
  96627. ;
  96628. return HardwareScalingOptimization;
  96629. }(SceneOptimization));
  96630. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  96631. /**
  96632. * Defines an optimization used to remove shadows
  96633. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96634. */
  96635. var ShadowsOptimization = /** @class */ (function (_super) {
  96636. __extends(ShadowsOptimization, _super);
  96637. function ShadowsOptimization() {
  96638. return _super !== null && _super.apply(this, arguments) || this;
  96639. }
  96640. /**
  96641. * Gets a string describing the action executed by the current optimization
  96642. * @return description string
  96643. */
  96644. ShadowsOptimization.prototype.getDescription = function () {
  96645. return "Turning shadows on/off";
  96646. };
  96647. /**
  96648. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96649. * @param scene defines the current scene where to apply this optimization
  96650. * @param optimizer defines the current optimizer
  96651. * @returns true if everything that can be done was applied
  96652. */
  96653. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  96654. scene.shadowsEnabled = optimizer.isInImprovementMode;
  96655. return true;
  96656. };
  96657. ;
  96658. return ShadowsOptimization;
  96659. }(SceneOptimization));
  96660. BABYLON.ShadowsOptimization = ShadowsOptimization;
  96661. /**
  96662. * Defines an optimization used to turn post-processes off
  96663. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96664. */
  96665. var PostProcessesOptimization = /** @class */ (function (_super) {
  96666. __extends(PostProcessesOptimization, _super);
  96667. function PostProcessesOptimization() {
  96668. return _super !== null && _super.apply(this, arguments) || this;
  96669. }
  96670. /**
  96671. * Gets a string describing the action executed by the current optimization
  96672. * @return description string
  96673. */
  96674. PostProcessesOptimization.prototype.getDescription = function () {
  96675. return "Turning post-processes on/off";
  96676. };
  96677. /**
  96678. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96679. * @param scene defines the current scene where to apply this optimization
  96680. * @param optimizer defines the current optimizer
  96681. * @returns true if everything that can be done was applied
  96682. */
  96683. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  96684. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  96685. return true;
  96686. };
  96687. ;
  96688. return PostProcessesOptimization;
  96689. }(SceneOptimization));
  96690. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  96691. /**
  96692. * Defines an optimization used to turn lens flares off
  96693. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96694. */
  96695. var LensFlaresOptimization = /** @class */ (function (_super) {
  96696. __extends(LensFlaresOptimization, _super);
  96697. function LensFlaresOptimization() {
  96698. return _super !== null && _super.apply(this, arguments) || this;
  96699. }
  96700. /**
  96701. * Gets a string describing the action executed by the current optimization
  96702. * @return description string
  96703. */
  96704. LensFlaresOptimization.prototype.getDescription = function () {
  96705. return "Turning lens flares on/off";
  96706. };
  96707. /**
  96708. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96709. * @param scene defines the current scene where to apply this optimization
  96710. * @param optimizer defines the current optimizer
  96711. * @returns true if everything that can be done was applied
  96712. */
  96713. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  96714. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  96715. return true;
  96716. };
  96717. ;
  96718. return LensFlaresOptimization;
  96719. }(SceneOptimization));
  96720. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  96721. /**
  96722. * Defines an optimization based on user defined callback.
  96723. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96724. */
  96725. var CustomOptimization = /** @class */ (function (_super) {
  96726. __extends(CustomOptimization, _super);
  96727. function CustomOptimization() {
  96728. return _super !== null && _super.apply(this, arguments) || this;
  96729. }
  96730. /**
  96731. * Gets a string describing the action executed by the current optimization
  96732. * @returns description string
  96733. */
  96734. CustomOptimization.prototype.getDescription = function () {
  96735. if (this.onGetDescription) {
  96736. return this.onGetDescription();
  96737. }
  96738. return "Running user defined callback";
  96739. };
  96740. /**
  96741. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96742. * @param scene defines the current scene where to apply this optimization
  96743. * @param optimizer defines the current optimizer
  96744. * @returns true if everything that can be done was applied
  96745. */
  96746. CustomOptimization.prototype.apply = function (scene, optimizer) {
  96747. if (this.onApply) {
  96748. return this.onApply(scene, optimizer);
  96749. }
  96750. return true;
  96751. };
  96752. ;
  96753. return CustomOptimization;
  96754. }(SceneOptimization));
  96755. BABYLON.CustomOptimization = CustomOptimization;
  96756. /**
  96757. * Defines an optimization used to turn particles off
  96758. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96759. */
  96760. var ParticlesOptimization = /** @class */ (function (_super) {
  96761. __extends(ParticlesOptimization, _super);
  96762. function ParticlesOptimization() {
  96763. return _super !== null && _super.apply(this, arguments) || this;
  96764. }
  96765. /**
  96766. * Gets a string describing the action executed by the current optimization
  96767. * @return description string
  96768. */
  96769. ParticlesOptimization.prototype.getDescription = function () {
  96770. return "Turning particles on/off";
  96771. };
  96772. /**
  96773. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96774. * @param scene defines the current scene where to apply this optimization
  96775. * @param optimizer defines the current optimizer
  96776. * @returns true if everything that can be done was applied
  96777. */
  96778. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  96779. scene.particlesEnabled = optimizer.isInImprovementMode;
  96780. return true;
  96781. };
  96782. ;
  96783. return ParticlesOptimization;
  96784. }(SceneOptimization));
  96785. BABYLON.ParticlesOptimization = ParticlesOptimization;
  96786. /**
  96787. * Defines an optimization used to turn render targets off
  96788. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96789. */
  96790. var RenderTargetsOptimization = /** @class */ (function (_super) {
  96791. __extends(RenderTargetsOptimization, _super);
  96792. function RenderTargetsOptimization() {
  96793. return _super !== null && _super.apply(this, arguments) || this;
  96794. }
  96795. /**
  96796. * Gets a string describing the action executed by the current optimization
  96797. * @return description string
  96798. */
  96799. RenderTargetsOptimization.prototype.getDescription = function () {
  96800. return "Turning render targets off";
  96801. };
  96802. /**
  96803. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96804. * @param scene defines the current scene where to apply this optimization
  96805. * @param optimizer defines the current optimizer
  96806. * @returns true if everything that can be done was applied
  96807. */
  96808. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  96809. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  96810. return true;
  96811. };
  96812. ;
  96813. return RenderTargetsOptimization;
  96814. }(SceneOptimization));
  96815. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  96816. /**
  96817. * Defines an optimization used to merge meshes with compatible materials
  96818. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96819. */
  96820. var MergeMeshesOptimization = /** @class */ (function (_super) {
  96821. __extends(MergeMeshesOptimization, _super);
  96822. function MergeMeshesOptimization() {
  96823. var _this = _super !== null && _super.apply(this, arguments) || this;
  96824. _this._canBeMerged = function (abstractMesh) {
  96825. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  96826. return false;
  96827. }
  96828. var mesh = abstractMesh;
  96829. if (mesh.isDisposed()) {
  96830. return false;
  96831. }
  96832. if (!mesh.isVisible || !mesh.isEnabled()) {
  96833. return false;
  96834. }
  96835. if (mesh.instances.length > 0) {
  96836. return false;
  96837. }
  96838. if (mesh.skeleton || mesh.hasLODLevels) {
  96839. return false;
  96840. }
  96841. return true;
  96842. };
  96843. return _this;
  96844. }
  96845. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  96846. /**
  96847. * Gets or sets a boolean which defines if optimization octree has to be updated
  96848. */
  96849. get: function () {
  96850. return MergeMeshesOptimization._UpdateSelectionTree;
  96851. },
  96852. /**
  96853. * Gets or sets a boolean which defines if optimization octree has to be updated
  96854. */
  96855. set: function (value) {
  96856. MergeMeshesOptimization._UpdateSelectionTree = value;
  96857. },
  96858. enumerable: true,
  96859. configurable: true
  96860. });
  96861. /**
  96862. * Gets a string describing the action executed by the current optimization
  96863. * @return description string
  96864. */
  96865. MergeMeshesOptimization.prototype.getDescription = function () {
  96866. return "Merging similar meshes together";
  96867. };
  96868. /**
  96869. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96870. * @param scene defines the current scene where to apply this optimization
  96871. * @param optimizer defines the current optimizer
  96872. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  96873. * @returns true if everything that can be done was applied
  96874. */
  96875. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  96876. var globalPool = scene.meshes.slice(0);
  96877. var globalLength = globalPool.length;
  96878. for (var index = 0; index < globalLength; index++) {
  96879. var currentPool = new Array();
  96880. var current = globalPool[index];
  96881. // Checks
  96882. if (!this._canBeMerged(current)) {
  96883. continue;
  96884. }
  96885. currentPool.push(current);
  96886. // Find compatible meshes
  96887. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  96888. var otherMesh = globalPool[subIndex];
  96889. if (!this._canBeMerged(otherMesh)) {
  96890. continue;
  96891. }
  96892. if (otherMesh.material !== current.material) {
  96893. continue;
  96894. }
  96895. if (otherMesh.checkCollisions !== current.checkCollisions) {
  96896. continue;
  96897. }
  96898. currentPool.push(otherMesh);
  96899. globalLength--;
  96900. globalPool.splice(subIndex, 1);
  96901. subIndex--;
  96902. }
  96903. if (currentPool.length < 2) {
  96904. continue;
  96905. }
  96906. // Merge meshes
  96907. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  96908. }
  96909. if (updateSelectionTree != undefined) {
  96910. if (updateSelectionTree) {
  96911. scene.createOrUpdateSelectionOctree();
  96912. }
  96913. }
  96914. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  96915. scene.createOrUpdateSelectionOctree();
  96916. }
  96917. return true;
  96918. };
  96919. ;
  96920. MergeMeshesOptimization._UpdateSelectionTree = false;
  96921. return MergeMeshesOptimization;
  96922. }(SceneOptimization));
  96923. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  96924. /**
  96925. * Defines a list of options used by SceneOptimizer
  96926. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96927. */
  96928. var SceneOptimizerOptions = /** @class */ (function () {
  96929. /**
  96930. * Creates a new list of options used by SceneOptimizer
  96931. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  96932. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  96933. */
  96934. function SceneOptimizerOptions(
  96935. /**
  96936. * Defines the target frame rate to reach (60 by default)
  96937. */
  96938. targetFrameRate,
  96939. /**
  96940. * Defines the interval between two checkes (2000ms by default)
  96941. */
  96942. trackerDuration) {
  96943. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  96944. if (trackerDuration === void 0) { trackerDuration = 2000; }
  96945. this.targetFrameRate = targetFrameRate;
  96946. this.trackerDuration = trackerDuration;
  96947. /**
  96948. * Gets the list of optimizations to apply
  96949. */
  96950. this.optimizations = new Array();
  96951. }
  96952. /**
  96953. * Add a new optimization
  96954. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  96955. * @returns the current SceneOptimizerOptions
  96956. */
  96957. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  96958. this.optimizations.push(optimization);
  96959. return this;
  96960. };
  96961. /**
  96962. * Add a new custom optimization
  96963. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  96964. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  96965. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96966. * @returns the current SceneOptimizerOptions
  96967. */
  96968. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  96969. if (priority === void 0) { priority = 0; }
  96970. var optimization = new CustomOptimization(priority);
  96971. optimization.onApply = onApply;
  96972. optimization.onGetDescription = onGetDescription;
  96973. this.optimizations.push(optimization);
  96974. return this;
  96975. };
  96976. /**
  96977. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  96978. * @param targetFrameRate defines the target frame rate (60 by default)
  96979. * @returns a SceneOptimizerOptions object
  96980. */
  96981. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  96982. var result = new SceneOptimizerOptions(targetFrameRate);
  96983. var priority = 0;
  96984. result.addOptimization(new MergeMeshesOptimization(priority));
  96985. result.addOptimization(new ShadowsOptimization(priority));
  96986. result.addOptimization(new LensFlaresOptimization(priority));
  96987. // Next priority
  96988. priority++;
  96989. result.addOptimization(new PostProcessesOptimization(priority));
  96990. result.addOptimization(new ParticlesOptimization(priority));
  96991. // Next priority
  96992. priority++;
  96993. result.addOptimization(new TextureOptimization(priority, 1024));
  96994. return result;
  96995. };
  96996. /**
  96997. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  96998. * @param targetFrameRate defines the target frame rate (60 by default)
  96999. * @returns a SceneOptimizerOptions object
  97000. */
  97001. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  97002. var result = new SceneOptimizerOptions(targetFrameRate);
  97003. var priority = 0;
  97004. result.addOptimization(new MergeMeshesOptimization(priority));
  97005. result.addOptimization(new ShadowsOptimization(priority));
  97006. result.addOptimization(new LensFlaresOptimization(priority));
  97007. // Next priority
  97008. priority++;
  97009. result.addOptimization(new PostProcessesOptimization(priority));
  97010. result.addOptimization(new ParticlesOptimization(priority));
  97011. // Next priority
  97012. priority++;
  97013. result.addOptimization(new TextureOptimization(priority, 512));
  97014. // Next priority
  97015. priority++;
  97016. result.addOptimization(new RenderTargetsOptimization(priority));
  97017. // Next priority
  97018. priority++;
  97019. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  97020. return result;
  97021. };
  97022. /**
  97023. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  97024. * @param targetFrameRate defines the target frame rate (60 by default)
  97025. * @returns a SceneOptimizerOptions object
  97026. */
  97027. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  97028. var result = new SceneOptimizerOptions(targetFrameRate);
  97029. var priority = 0;
  97030. result.addOptimization(new MergeMeshesOptimization(priority));
  97031. result.addOptimization(new ShadowsOptimization(priority));
  97032. result.addOptimization(new LensFlaresOptimization(priority));
  97033. // Next priority
  97034. priority++;
  97035. result.addOptimization(new PostProcessesOptimization(priority));
  97036. result.addOptimization(new ParticlesOptimization(priority));
  97037. // Next priority
  97038. priority++;
  97039. result.addOptimization(new TextureOptimization(priority, 256));
  97040. // Next priority
  97041. priority++;
  97042. result.addOptimization(new RenderTargetsOptimization(priority));
  97043. // Next priority
  97044. priority++;
  97045. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  97046. return result;
  97047. };
  97048. return SceneOptimizerOptions;
  97049. }());
  97050. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  97051. /**
  97052. * Class used to run optimizations in order to reach a target frame rate
  97053. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97054. */
  97055. var SceneOptimizer = /** @class */ (function () {
  97056. /**
  97057. * Creates a new SceneOptimizer
  97058. * @param scene defines the scene to work on
  97059. * @param options defines the options to use with the SceneOptimizer
  97060. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  97061. * @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)
  97062. */
  97063. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  97064. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  97065. if (improvementMode === void 0) { improvementMode = false; }
  97066. var _this = this;
  97067. this._isRunning = false;
  97068. this._currentPriorityLevel = 0;
  97069. this._targetFrameRate = 60;
  97070. this._trackerDuration = 2000;
  97071. this._currentFrameRate = 0;
  97072. this._improvementMode = false;
  97073. /**
  97074. * Defines an observable called when the optimizer reaches the target frame rate
  97075. */
  97076. this.onSuccessObservable = new BABYLON.Observable();
  97077. /**
  97078. * Defines an observable called when the optimizer enables an optimization
  97079. */
  97080. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  97081. /**
  97082. * Defines an observable called when the optimizer is not able to reach the target frame rate
  97083. */
  97084. this.onFailureObservable = new BABYLON.Observable();
  97085. if (!options) {
  97086. this._options = new SceneOptimizerOptions();
  97087. }
  97088. else {
  97089. this._options = options;
  97090. }
  97091. if (this._options.targetFrameRate) {
  97092. this._targetFrameRate = this._options.targetFrameRate;
  97093. }
  97094. if (this._options.trackerDuration) {
  97095. this._trackerDuration = this._options.trackerDuration;
  97096. }
  97097. if (autoGeneratePriorities) {
  97098. var priority = 0;
  97099. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  97100. var optim = _a[_i];
  97101. optim.priority = priority++;
  97102. }
  97103. }
  97104. this._improvementMode = improvementMode;
  97105. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97106. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  97107. _this._sceneDisposeObserver = null;
  97108. _this.dispose();
  97109. });
  97110. }
  97111. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  97112. /**
  97113. * Gets a boolean indicating if the optimizer is in improvement mode
  97114. */
  97115. get: function () {
  97116. return this._improvementMode;
  97117. },
  97118. enumerable: true,
  97119. configurable: true
  97120. });
  97121. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  97122. /**
  97123. * Gets the current priority level (0 at start)
  97124. */
  97125. get: function () {
  97126. return this._currentPriorityLevel;
  97127. },
  97128. enumerable: true,
  97129. configurable: true
  97130. });
  97131. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  97132. /**
  97133. * Gets the current frame rate checked by the SceneOptimizer
  97134. */
  97135. get: function () {
  97136. return this._currentFrameRate;
  97137. },
  97138. enumerable: true,
  97139. configurable: true
  97140. });
  97141. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  97142. /**
  97143. * Gets or sets the current target frame rate (60 by default)
  97144. */
  97145. get: function () {
  97146. return this._targetFrameRate;
  97147. },
  97148. /**
  97149. * Gets or sets the current target frame rate (60 by default)
  97150. */
  97151. set: function (value) {
  97152. this._targetFrameRate = value;
  97153. },
  97154. enumerable: true,
  97155. configurable: true
  97156. });
  97157. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  97158. /**
  97159. * Gets or sets the current interval between two checks (every 2000ms by default)
  97160. */
  97161. get: function () {
  97162. return this._trackerDuration;
  97163. },
  97164. /**
  97165. * Gets or sets the current interval between two checks (every 2000ms by default)
  97166. */
  97167. set: function (value) {
  97168. this._trackerDuration = value;
  97169. },
  97170. enumerable: true,
  97171. configurable: true
  97172. });
  97173. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  97174. /**
  97175. * Gets the list of active optimizations
  97176. */
  97177. get: function () {
  97178. return this._options.optimizations;
  97179. },
  97180. enumerable: true,
  97181. configurable: true
  97182. });
  97183. /**
  97184. * Stops the current optimizer
  97185. */
  97186. SceneOptimizer.prototype.stop = function () {
  97187. this._isRunning = false;
  97188. };
  97189. /**
  97190. * Reset the optimizer to initial step (current priority level = 0)
  97191. */
  97192. SceneOptimizer.prototype.reset = function () {
  97193. this._currentPriorityLevel = 0;
  97194. };
  97195. /**
  97196. * Start the optimizer. By default it will try to reach a specific framerate
  97197. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  97198. */
  97199. SceneOptimizer.prototype.start = function () {
  97200. var _this = this;
  97201. if (this._isRunning) {
  97202. return;
  97203. }
  97204. this._isRunning = true;
  97205. // Let's wait for the scene to be ready before running our check
  97206. this._scene.executeWhenReady(function () {
  97207. setTimeout(function () {
  97208. _this._checkCurrentState();
  97209. }, _this._trackerDuration);
  97210. });
  97211. };
  97212. SceneOptimizer.prototype._checkCurrentState = function () {
  97213. var _this = this;
  97214. if (!this._isRunning) {
  97215. return;
  97216. }
  97217. var scene = this._scene;
  97218. var options = this._options;
  97219. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  97220. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  97221. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  97222. this._isRunning = false;
  97223. this.onSuccessObservable.notifyObservers(this);
  97224. return;
  97225. }
  97226. // Apply current level of optimizations
  97227. var allDone = true;
  97228. var noOptimizationApplied = true;
  97229. for (var index = 0; index < options.optimizations.length; index++) {
  97230. var optimization = options.optimizations[index];
  97231. if (optimization.priority === this._currentPriorityLevel) {
  97232. noOptimizationApplied = false;
  97233. allDone = allDone && optimization.apply(scene, this);
  97234. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  97235. }
  97236. }
  97237. // If no optimization was applied, this is a failure :(
  97238. if (noOptimizationApplied) {
  97239. this._isRunning = false;
  97240. this.onFailureObservable.notifyObservers(this);
  97241. return;
  97242. }
  97243. // If all optimizations were done, move to next level
  97244. if (allDone) {
  97245. this._currentPriorityLevel++;
  97246. }
  97247. // Let's the system running for a specific amount of time before checking FPS
  97248. scene.executeWhenReady(function () {
  97249. setTimeout(function () {
  97250. _this._checkCurrentState();
  97251. }, _this._trackerDuration);
  97252. });
  97253. };
  97254. /**
  97255. * Release all resources
  97256. */
  97257. SceneOptimizer.prototype.dispose = function () {
  97258. this.stop();
  97259. this.onSuccessObservable.clear();
  97260. this.onFailureObservable.clear();
  97261. this.onNewOptimizationAppliedObservable.clear();
  97262. if (this._sceneDisposeObserver) {
  97263. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  97264. }
  97265. };
  97266. /**
  97267. * Helper function to create a SceneOptimizer with one single line of code
  97268. * @param scene defines the scene to work on
  97269. * @param options defines the options to use with the SceneOptimizer
  97270. * @param onSuccess defines a callback to call on success
  97271. * @param onFailure defines a callback to call on failure
  97272. * @returns the new SceneOptimizer object
  97273. */
  97274. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  97275. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  97276. if (onSuccess) {
  97277. optimizer.onSuccessObservable.add(function () {
  97278. onSuccess();
  97279. });
  97280. }
  97281. if (onFailure) {
  97282. optimizer.onFailureObservable.add(function () {
  97283. onFailure();
  97284. });
  97285. }
  97286. optimizer.start();
  97287. return optimizer;
  97288. };
  97289. return SceneOptimizer;
  97290. }());
  97291. BABYLON.SceneOptimizer = SceneOptimizer;
  97292. })(BABYLON || (BABYLON = {}));
  97293. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  97294. var BABYLON;
  97295. (function (BABYLON) {
  97296. var OutlineRenderer = /** @class */ (function () {
  97297. function OutlineRenderer(scene) {
  97298. this.zOffset = 1;
  97299. this._scene = scene;
  97300. }
  97301. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  97302. var _this = this;
  97303. if (useOverlay === void 0) { useOverlay = false; }
  97304. var scene = this._scene;
  97305. var engine = this._scene.getEngine();
  97306. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97307. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  97308. return;
  97309. }
  97310. var mesh = subMesh.getRenderingMesh();
  97311. var material = subMesh.getMaterial();
  97312. if (!material || !scene.activeCamera) {
  97313. return;
  97314. }
  97315. engine.enableEffect(this._effect);
  97316. // Logarithmic depth
  97317. if (material.useLogarithmicDepth) {
  97318. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  97319. }
  97320. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  97321. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  97322. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  97323. // Bones
  97324. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97325. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97326. }
  97327. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  97328. // Alpha test
  97329. if (material && material.needAlphaTesting()) {
  97330. var alphaTexture = material.getAlphaTestTexture();
  97331. if (alphaTexture) {
  97332. this._effect.setTexture("diffuseSampler", alphaTexture);
  97333. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  97334. }
  97335. }
  97336. engine.setZOffset(-this.zOffset);
  97337. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  97338. engine.setZOffset(0);
  97339. };
  97340. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  97341. var defines = [];
  97342. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  97343. var mesh = subMesh.getMesh();
  97344. var material = subMesh.getMaterial();
  97345. if (material) {
  97346. // Alpha test
  97347. if (material.needAlphaTesting()) {
  97348. defines.push("#define ALPHATEST");
  97349. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97350. attribs.push(BABYLON.VertexBuffer.UVKind);
  97351. defines.push("#define UV1");
  97352. }
  97353. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  97354. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97355. defines.push("#define UV2");
  97356. }
  97357. }
  97358. //Logarithmic depth
  97359. if (material.useLogarithmicDepth) {
  97360. defines.push("#define LOGARITHMICDEPTH");
  97361. }
  97362. }
  97363. // Bones
  97364. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97365. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97366. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97367. if (mesh.numBoneInfluencers > 4) {
  97368. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97369. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97370. }
  97371. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97372. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  97373. }
  97374. else {
  97375. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97376. }
  97377. // Instances
  97378. if (useInstances) {
  97379. defines.push("#define INSTANCES");
  97380. attribs.push("world0");
  97381. attribs.push("world1");
  97382. attribs.push("world2");
  97383. attribs.push("world3");
  97384. }
  97385. // Get correct effect
  97386. var join = defines.join("\n");
  97387. if (this._cachedDefines !== join) {
  97388. this._cachedDefines = join;
  97389. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  97390. }
  97391. return this._effect.isReady();
  97392. };
  97393. return OutlineRenderer;
  97394. }());
  97395. BABYLON.OutlineRenderer = OutlineRenderer;
  97396. })(BABYLON || (BABYLON = {}));
  97397. //# sourceMappingURL=babylon.outlineRenderer.js.map
  97398. var BABYLON;
  97399. (function (BABYLON) {
  97400. var FaceAdjacencies = /** @class */ (function () {
  97401. function FaceAdjacencies() {
  97402. this.edges = new Array();
  97403. this.edgesConnectedCount = 0;
  97404. }
  97405. return FaceAdjacencies;
  97406. }());
  97407. var EdgesRenderer = /** @class */ (function () {
  97408. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  97409. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  97410. if (epsilon === void 0) { epsilon = 0.95; }
  97411. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  97412. this.edgesWidthScalerForOrthographic = 1000.0;
  97413. this.edgesWidthScalerForPerspective = 50.0;
  97414. this._linesPositions = new Array();
  97415. this._linesNormals = new Array();
  97416. this._linesIndices = new Array();
  97417. this._buffers = {};
  97418. this._checkVerticesInsteadOfIndices = false;
  97419. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  97420. this.isEnabled = true;
  97421. this._source = source;
  97422. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  97423. this._epsilon = epsilon;
  97424. this._prepareRessources();
  97425. this._generateEdgesLines();
  97426. }
  97427. EdgesRenderer.prototype._prepareRessources = function () {
  97428. if (this._lineShader) {
  97429. return;
  97430. }
  97431. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  97432. attributes: ["position", "normal"],
  97433. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  97434. });
  97435. this._lineShader.disableDepthWrite = true;
  97436. this._lineShader.backFaceCulling = false;
  97437. };
  97438. EdgesRenderer.prototype._rebuild = function () {
  97439. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  97440. if (buffer) {
  97441. buffer._rebuild();
  97442. }
  97443. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  97444. if (buffer) {
  97445. buffer._rebuild();
  97446. }
  97447. var scene = this._source.getScene();
  97448. var engine = scene.getEngine();
  97449. this._ib = engine.createIndexBuffer(this._linesIndices);
  97450. };
  97451. EdgesRenderer.prototype.dispose = function () {
  97452. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  97453. if (buffer) {
  97454. buffer.dispose();
  97455. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  97456. }
  97457. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  97458. if (buffer) {
  97459. buffer.dispose();
  97460. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  97461. }
  97462. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  97463. this._lineShader.dispose();
  97464. };
  97465. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  97466. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  97467. return 0;
  97468. }
  97469. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  97470. return 1;
  97471. }
  97472. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  97473. return 2;
  97474. }
  97475. return -1;
  97476. };
  97477. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  97478. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  97479. return 0;
  97480. }
  97481. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  97482. return 1;
  97483. }
  97484. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  97485. return 2;
  97486. }
  97487. return -1;
  97488. };
  97489. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  97490. var needToCreateLine;
  97491. if (edge === undefined) {
  97492. needToCreateLine = true;
  97493. }
  97494. else {
  97495. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  97496. needToCreateLine = dotProduct < this._epsilon;
  97497. }
  97498. if (needToCreateLine) {
  97499. var offset = this._linesPositions.length / 3;
  97500. var normal = p0.subtract(p1);
  97501. normal.normalize();
  97502. // Positions
  97503. this._linesPositions.push(p0.x);
  97504. this._linesPositions.push(p0.y);
  97505. this._linesPositions.push(p0.z);
  97506. this._linesPositions.push(p0.x);
  97507. this._linesPositions.push(p0.y);
  97508. this._linesPositions.push(p0.z);
  97509. this._linesPositions.push(p1.x);
  97510. this._linesPositions.push(p1.y);
  97511. this._linesPositions.push(p1.z);
  97512. this._linesPositions.push(p1.x);
  97513. this._linesPositions.push(p1.y);
  97514. this._linesPositions.push(p1.z);
  97515. // Normals
  97516. this._linesNormals.push(p1.x);
  97517. this._linesNormals.push(p1.y);
  97518. this._linesNormals.push(p1.z);
  97519. this._linesNormals.push(-1);
  97520. this._linesNormals.push(p1.x);
  97521. this._linesNormals.push(p1.y);
  97522. this._linesNormals.push(p1.z);
  97523. this._linesNormals.push(1);
  97524. this._linesNormals.push(p0.x);
  97525. this._linesNormals.push(p0.y);
  97526. this._linesNormals.push(p0.z);
  97527. this._linesNormals.push(-1);
  97528. this._linesNormals.push(p0.x);
  97529. this._linesNormals.push(p0.y);
  97530. this._linesNormals.push(p0.z);
  97531. this._linesNormals.push(1);
  97532. // Indices
  97533. this._linesIndices.push(offset);
  97534. this._linesIndices.push(offset + 1);
  97535. this._linesIndices.push(offset + 2);
  97536. this._linesIndices.push(offset);
  97537. this._linesIndices.push(offset + 2);
  97538. this._linesIndices.push(offset + 3);
  97539. }
  97540. };
  97541. EdgesRenderer.prototype._generateEdgesLines = function () {
  97542. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97543. var indices = this._source.getIndices();
  97544. if (!indices || !positions) {
  97545. return;
  97546. }
  97547. // First let's find adjacencies
  97548. var adjacencies = new Array();
  97549. var faceNormals = new Array();
  97550. var index;
  97551. var faceAdjacencies;
  97552. // Prepare faces
  97553. for (index = 0; index < indices.length; index += 3) {
  97554. faceAdjacencies = new FaceAdjacencies();
  97555. var p0Index = indices[index];
  97556. var p1Index = indices[index + 1];
  97557. var p2Index = indices[index + 2];
  97558. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  97559. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  97560. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  97561. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  97562. faceNormal.normalize();
  97563. faceNormals.push(faceNormal);
  97564. adjacencies.push(faceAdjacencies);
  97565. }
  97566. // Scan
  97567. for (index = 0; index < adjacencies.length; index++) {
  97568. faceAdjacencies = adjacencies[index];
  97569. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  97570. var otherFaceAdjacencies = adjacencies[otherIndex];
  97571. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  97572. break;
  97573. }
  97574. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  97575. continue;
  97576. }
  97577. var otherP0 = indices[otherIndex * 3];
  97578. var otherP1 = indices[otherIndex * 3 + 1];
  97579. var otherP2 = indices[otherIndex * 3 + 2];
  97580. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  97581. var otherEdgeIndex = 0;
  97582. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  97583. continue;
  97584. }
  97585. switch (edgeIndex) {
  97586. case 0:
  97587. if (this._checkVerticesInsteadOfIndices) {
  97588. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97589. }
  97590. else {
  97591. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  97592. }
  97593. break;
  97594. case 1:
  97595. if (this._checkVerticesInsteadOfIndices) {
  97596. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97597. }
  97598. else {
  97599. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  97600. }
  97601. break;
  97602. case 2:
  97603. if (this._checkVerticesInsteadOfIndices) {
  97604. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97605. }
  97606. else {
  97607. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  97608. }
  97609. break;
  97610. }
  97611. if (otherEdgeIndex === -1) {
  97612. continue;
  97613. }
  97614. faceAdjacencies.edges[edgeIndex] = otherIndex;
  97615. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  97616. faceAdjacencies.edgesConnectedCount++;
  97617. otherFaceAdjacencies.edgesConnectedCount++;
  97618. if (faceAdjacencies.edgesConnectedCount === 3) {
  97619. break;
  97620. }
  97621. }
  97622. }
  97623. }
  97624. // Create lines
  97625. for (index = 0; index < adjacencies.length; index++) {
  97626. // 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
  97627. var current = adjacencies[index];
  97628. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  97629. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  97630. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  97631. }
  97632. // Merge into a single mesh
  97633. var engine = this._source.getScene().getEngine();
  97634. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  97635. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  97636. this._ib = engine.createIndexBuffer(this._linesIndices);
  97637. this._indicesCount = this._linesIndices.length;
  97638. };
  97639. EdgesRenderer.prototype.render = function () {
  97640. var scene = this._source.getScene();
  97641. if (!this._lineShader.isReady() || !scene.activeCamera) {
  97642. return;
  97643. }
  97644. var engine = scene.getEngine();
  97645. this._lineShader._preBind();
  97646. // VBOs
  97647. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  97648. scene.resetCachedMaterial();
  97649. this._lineShader.setColor4("color", this._source.edgesColor);
  97650. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  97651. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  97652. }
  97653. else {
  97654. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  97655. }
  97656. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  97657. this._lineShader.bind(this._source.getWorldMatrix());
  97658. // Draw order
  97659. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  97660. this._lineShader.unbind();
  97661. engine.setDepthWrite(true);
  97662. };
  97663. return EdgesRenderer;
  97664. }());
  97665. BABYLON.EdgesRenderer = EdgesRenderer;
  97666. })(BABYLON || (BABYLON = {}));
  97667. //# sourceMappingURL=babylon.edgesRenderer.js.map
  97668. var BABYLON;
  97669. (function (BABYLON) {
  97670. // Adds the parser to the scene parsers.
  97671. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  97672. if (parsedData.effectLayers) {
  97673. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  97674. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  97675. container.effectLayers.push(effectLayer);
  97676. }
  97677. }
  97678. });
  97679. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  97680. var index = this.effectLayers.indexOf(toRemove);
  97681. if (index !== -1) {
  97682. this.effectLayers.splice(index, 1);
  97683. }
  97684. return index;
  97685. };
  97686. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  97687. this.effectLayers.push(newEffectLayer);
  97688. };
  97689. /**
  97690. * Defines the layer scene component responsible to manage any effect layers
  97691. * in a given scene.
  97692. */
  97693. var EffectLayerSceneComponent = /** @class */ (function () {
  97694. /**
  97695. * Creates a new instance of the component for the given scene
  97696. * @param scene Defines the scene to register the component in
  97697. */
  97698. function EffectLayerSceneComponent(scene) {
  97699. /**
  97700. * The component name helpfull to identify the component in the list of scene components.
  97701. */
  97702. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  97703. this._renderEffects = false;
  97704. this._needStencil = false;
  97705. this._previousStencilState = false;
  97706. this.scene = scene;
  97707. this._engine = scene.getEngine();
  97708. scene.effectLayers = new Array();
  97709. }
  97710. /**
  97711. * Registers the component in a given scene
  97712. */
  97713. EffectLayerSceneComponent.prototype.register = function () {
  97714. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  97715. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  97716. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  97717. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  97718. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  97719. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  97720. };
  97721. /**
  97722. * Rebuilds the elements related to this component in case of
  97723. * context lost for instance.
  97724. */
  97725. EffectLayerSceneComponent.prototype.rebuild = function () {
  97726. var layers = this.scene.effectLayers;
  97727. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  97728. var effectLayer = layers_1[_i];
  97729. effectLayer._rebuild();
  97730. }
  97731. };
  97732. /**
  97733. * Serializes the component data to the specified json object
  97734. * @param serializationObject The object to serialize to
  97735. */
  97736. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  97737. // Effect layers
  97738. serializationObject.effectLayers = [];
  97739. var layers = this.scene.effectLayers;
  97740. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  97741. var effectLayer = layers_2[_i];
  97742. if (effectLayer.serialize) {
  97743. serializationObject.effectLayers.push(effectLayer.serialize());
  97744. }
  97745. }
  97746. };
  97747. /**
  97748. * Adds all the element from the container to the scene
  97749. * @param container the container holding the elements
  97750. */
  97751. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  97752. var _this = this;
  97753. if (!container.effectLayers) {
  97754. return;
  97755. }
  97756. container.effectLayers.forEach(function (o) {
  97757. _this.scene.addEffectLayer(o);
  97758. });
  97759. };
  97760. /**
  97761. * Removes all the elements in the container from the scene
  97762. * @param container contains the elements to remove
  97763. */
  97764. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  97765. var _this = this;
  97766. if (!container.effectLayers) {
  97767. return;
  97768. }
  97769. container.effectLayers.forEach(function (o) {
  97770. _this.scene.removeEffectLayer(o);
  97771. });
  97772. };
  97773. /**
  97774. * Disposes the component and the associated ressources.
  97775. */
  97776. EffectLayerSceneComponent.prototype.dispose = function () {
  97777. var layers = this.scene.effectLayers;
  97778. while (layers.length) {
  97779. layers[0].dispose();
  97780. }
  97781. };
  97782. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  97783. var layers = this.scene.effectLayers;
  97784. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  97785. var layer = layers_3[_i];
  97786. if (!layer.hasMesh(mesh)) {
  97787. continue;
  97788. }
  97789. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  97790. var subMesh = _b[_a];
  97791. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  97792. return false;
  97793. }
  97794. }
  97795. }
  97796. return true;
  97797. };
  97798. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  97799. this._renderEffects = false;
  97800. this._needStencil = false;
  97801. var layers = this.scene.effectLayers;
  97802. if (layers && layers.length > 0) {
  97803. this._previousStencilState = this._engine.getStencilBuffer();
  97804. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  97805. var effectLayer = layers_4[_i];
  97806. if (effectLayer.shouldRender() &&
  97807. (!effectLayer.camera ||
  97808. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  97809. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  97810. this._renderEffects = true;
  97811. this._needStencil = this._needStencil || effectLayer.needStencil();
  97812. var renderTarget = effectLayer._mainTexture;
  97813. if (renderTarget._shouldRender()) {
  97814. this.scene.incrementRenderId();
  97815. renderTarget.render(false, false);
  97816. }
  97817. }
  97818. }
  97819. this.scene.incrementRenderId();
  97820. }
  97821. };
  97822. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  97823. // Activate effect Layer stencil
  97824. if (this._needStencil) {
  97825. this._engine.setStencilBuffer(true);
  97826. }
  97827. };
  97828. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  97829. // Restore effect Layer stencil
  97830. if (this._needStencil) {
  97831. this._engine.setStencilBuffer(this._previousStencilState);
  97832. }
  97833. };
  97834. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  97835. if (this._renderEffects) {
  97836. this._engine.setDepthBuffer(false);
  97837. var layers = this.scene.effectLayers;
  97838. for (var i = 0; i < layers.length; i++) {
  97839. var effectLayer = layers[i];
  97840. if (effectLayer.renderingGroupId === renderingGroupId) {
  97841. if (effectLayer.shouldRender()) {
  97842. effectLayer.render();
  97843. }
  97844. }
  97845. }
  97846. this._engine.setDepthBuffer(true);
  97847. }
  97848. };
  97849. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  97850. if (this._renderEffects) {
  97851. this._draw(-1);
  97852. }
  97853. };
  97854. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  97855. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  97856. this._draw(index);
  97857. }
  97858. };
  97859. return EffectLayerSceneComponent;
  97860. }());
  97861. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  97862. })(BABYLON || (BABYLON = {}));
  97863. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  97864. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97865. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97866. s = arguments[i];
  97867. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97868. t[p] = s[p];
  97869. }
  97870. return t;
  97871. };
  97872. var BABYLON;
  97873. (function (BABYLON) {
  97874. /**
  97875. * The effect layer Helps adding post process effect blended with the main pass.
  97876. *
  97877. * This can be for instance use to generate glow or higlight effects on the scene.
  97878. *
  97879. * The effect layer class can not be used directly and is intented to inherited from to be
  97880. * customized per effects.
  97881. */
  97882. var EffectLayer = /** @class */ (function () {
  97883. /**
  97884. * Instantiates a new effect Layer and references it in the scene.
  97885. * @param name The name of the layer
  97886. * @param scene The scene to use the layer in
  97887. */
  97888. function EffectLayer(
  97889. /** The Friendly of the effect in the scene */
  97890. name, scene) {
  97891. this._vertexBuffers = {};
  97892. this._maxSize = 0;
  97893. this._mainTextureDesiredSize = { width: 0, height: 0 };
  97894. this._shouldRender = true;
  97895. this._postProcesses = [];
  97896. this._textures = [];
  97897. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  97898. /**
  97899. * The clear color of the texture used to generate the glow map.
  97900. */
  97901. this.neutralColor = new BABYLON.Color4();
  97902. /**
  97903. * Specifies wether the highlight layer is enabled or not.
  97904. */
  97905. this.isEnabled = true;
  97906. /**
  97907. * An event triggered when the effect layer has been disposed.
  97908. */
  97909. this.onDisposeObservable = new BABYLON.Observable();
  97910. /**
  97911. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  97912. */
  97913. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  97914. /**
  97915. * An event triggered when the generated texture is being merged in the scene.
  97916. */
  97917. this.onBeforeComposeObservable = new BABYLON.Observable();
  97918. /**
  97919. * An event triggered when the generated texture has been merged in the scene.
  97920. */
  97921. this.onAfterComposeObservable = new BABYLON.Observable();
  97922. /**
  97923. * An event triggered when the efffect layer changes its size.
  97924. */
  97925. this.onSizeChangedObservable = new BABYLON.Observable();
  97926. this.name = name;
  97927. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97928. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  97929. if (!component) {
  97930. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  97931. this._scene._addComponent(component);
  97932. }
  97933. this._engine = this._scene.getEngine();
  97934. this._maxSize = this._engine.getCaps().maxTextureSize;
  97935. this._scene.effectLayers.push(this);
  97936. // Generate Buffers
  97937. this._generateIndexBuffer();
  97938. this._genrateVertexBuffer();
  97939. }
  97940. Object.defineProperty(EffectLayer.prototype, "camera", {
  97941. /**
  97942. * Gets the camera attached to the layer.
  97943. */
  97944. get: function () {
  97945. return this._effectLayerOptions.camera;
  97946. },
  97947. enumerable: true,
  97948. configurable: true
  97949. });
  97950. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  97951. /**
  97952. * Gets the rendering group id the layer should render in.
  97953. */
  97954. get: function () {
  97955. return this._effectLayerOptions.renderingGroupId;
  97956. },
  97957. enumerable: true,
  97958. configurable: true
  97959. });
  97960. /**
  97961. * Initializes the effect layer with the required options.
  97962. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  97963. */
  97964. EffectLayer.prototype._init = function (options) {
  97965. // Adapt options
  97966. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97967. this._setMainTextureSize();
  97968. this._createMainTexture();
  97969. this._createTextureAndPostProcesses();
  97970. this._mergeEffect = this._createMergeEffect();
  97971. };
  97972. /**
  97973. * Generates the index buffer of the full screen quad blending to the main canvas.
  97974. */
  97975. EffectLayer.prototype._generateIndexBuffer = function () {
  97976. // Indices
  97977. var indices = [];
  97978. indices.push(0);
  97979. indices.push(1);
  97980. indices.push(2);
  97981. indices.push(0);
  97982. indices.push(2);
  97983. indices.push(3);
  97984. this._indexBuffer = this._engine.createIndexBuffer(indices);
  97985. };
  97986. /**
  97987. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  97988. */
  97989. EffectLayer.prototype._genrateVertexBuffer = function () {
  97990. // VBO
  97991. var vertices = [];
  97992. vertices.push(1, 1);
  97993. vertices.push(-1, 1);
  97994. vertices.push(-1, -1);
  97995. vertices.push(1, -1);
  97996. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97997. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97998. };
  97999. /**
  98000. * Sets the main texture desired size which is the closest power of two
  98001. * of the engine canvas size.
  98002. */
  98003. EffectLayer.prototype._setMainTextureSize = function () {
  98004. if (this._effectLayerOptions.mainTextureFixedSize) {
  98005. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  98006. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  98007. }
  98008. else {
  98009. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  98010. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  98011. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  98012. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  98013. }
  98014. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  98015. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  98016. };
  98017. /**
  98018. * Creates the main texture for the effect layer.
  98019. */
  98020. EffectLayer.prototype._createMainTexture = function () {
  98021. var _this = this;
  98022. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  98023. width: this._mainTextureDesiredSize.width,
  98024. height: this._mainTextureDesiredSize.height
  98025. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98026. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  98027. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98028. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98029. this._mainTexture.anisotropicFilteringLevel = 1;
  98030. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98031. this._mainTexture.renderParticles = false;
  98032. this._mainTexture.renderList = null;
  98033. this._mainTexture.ignoreCameraViewport = true;
  98034. // Custom render function
  98035. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  98036. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  98037. var index;
  98038. var engine = _this._scene.getEngine();
  98039. if (depthOnlySubMeshes.length) {
  98040. engine.setColorWrite(false);
  98041. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  98042. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  98043. }
  98044. engine.setColorWrite(true);
  98045. }
  98046. for (index = 0; index < opaqueSubMeshes.length; index++) {
  98047. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  98048. }
  98049. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  98050. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  98051. }
  98052. for (index = 0; index < transparentSubMeshes.length; index++) {
  98053. _this._renderSubMesh(transparentSubMeshes.data[index]);
  98054. }
  98055. };
  98056. this._mainTexture.onClearObservable.add(function (engine) {
  98057. engine.clear(_this.neutralColor, true, true, true);
  98058. });
  98059. };
  98060. /**
  98061. * Checks for the readiness of the element composing the layer.
  98062. * @param subMesh the mesh to check for
  98063. * @param useInstances specify wether or not to use instances to render the mesh
  98064. * @param emissiveTexture the associated emissive texture used to generate the glow
  98065. * @return true if ready otherwise, false
  98066. */
  98067. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  98068. var material = subMesh.getMaterial();
  98069. if (!material) {
  98070. return false;
  98071. }
  98072. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  98073. return false;
  98074. }
  98075. var defines = [];
  98076. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98077. var mesh = subMesh.getMesh();
  98078. var uv1 = false;
  98079. var uv2 = false;
  98080. // Alpha test
  98081. if (material && material.needAlphaTesting()) {
  98082. var alphaTexture = material.getAlphaTestTexture();
  98083. if (alphaTexture) {
  98084. defines.push("#define ALPHATEST");
  98085. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  98086. alphaTexture.coordinatesIndex === 1) {
  98087. defines.push("#define DIFFUSEUV2");
  98088. uv2 = true;
  98089. }
  98090. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  98091. defines.push("#define DIFFUSEUV1");
  98092. uv1 = true;
  98093. }
  98094. }
  98095. }
  98096. // Emissive
  98097. if (emissiveTexture) {
  98098. defines.push("#define EMISSIVE");
  98099. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  98100. emissiveTexture.coordinatesIndex === 1) {
  98101. defines.push("#define EMISSIVEUV2");
  98102. uv2 = true;
  98103. }
  98104. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  98105. defines.push("#define EMISSIVEUV1");
  98106. uv1 = true;
  98107. }
  98108. }
  98109. if (uv1) {
  98110. attribs.push(BABYLON.VertexBuffer.UVKind);
  98111. defines.push("#define UV1");
  98112. }
  98113. if (uv2) {
  98114. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98115. defines.push("#define UV2");
  98116. }
  98117. // Bones
  98118. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  98119. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  98120. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  98121. if (mesh.numBoneInfluencers > 4) {
  98122. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  98123. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  98124. }
  98125. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  98126. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  98127. }
  98128. else {
  98129. defines.push("#define NUM_BONE_INFLUENCERS 0");
  98130. }
  98131. // Morph targets
  98132. var manager = mesh.morphTargetManager;
  98133. var morphInfluencers = 0;
  98134. if (manager) {
  98135. if (manager.numInfluencers > 0) {
  98136. defines.push("#define MORPHTARGETS");
  98137. morphInfluencers = manager.numInfluencers;
  98138. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  98139. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  98140. }
  98141. }
  98142. // Instances
  98143. if (useInstances) {
  98144. defines.push("#define INSTANCES");
  98145. attribs.push("world0");
  98146. attribs.push("world1");
  98147. attribs.push("world2");
  98148. attribs.push("world3");
  98149. }
  98150. // Get correct effect
  98151. var join = defines.join("\n");
  98152. if (this._cachedDefines !== join) {
  98153. this._cachedDefines = join;
  98154. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  98155. }
  98156. return this._effectLayerMapGenerationEffect.isReady();
  98157. };
  98158. /**
  98159. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  98160. */
  98161. EffectLayer.prototype.render = function () {
  98162. var currentEffect = this._mergeEffect;
  98163. // Check
  98164. if (!currentEffect.isReady())
  98165. return;
  98166. for (var i = 0; i < this._postProcesses.length; i++) {
  98167. if (!this._postProcesses[i].isReady()) {
  98168. return;
  98169. }
  98170. }
  98171. var engine = this._scene.getEngine();
  98172. this.onBeforeComposeObservable.notifyObservers(this);
  98173. // Render
  98174. engine.enableEffect(currentEffect);
  98175. engine.setState(false);
  98176. // VBOs
  98177. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98178. // Cache
  98179. var previousAlphaMode = engine.getAlphaMode();
  98180. // Go Blend.
  98181. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  98182. // Blends the map on the main canvas.
  98183. this._internalRender(currentEffect);
  98184. // Restore Alpha
  98185. engine.setAlphaMode(previousAlphaMode);
  98186. this.onAfterComposeObservable.notifyObservers(this);
  98187. // Handle size changes.
  98188. var size = this._mainTexture.getSize();
  98189. this._setMainTextureSize();
  98190. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  98191. // Recreate RTT and post processes on size change.
  98192. this.onSizeChangedObservable.notifyObservers(this);
  98193. this._disposeTextureAndPostProcesses();
  98194. this._createMainTexture();
  98195. this._createTextureAndPostProcesses();
  98196. }
  98197. };
  98198. /**
  98199. * Determine if a given mesh will be used in the current effect.
  98200. * @param mesh mesh to test
  98201. * @returns true if the mesh will be used
  98202. */
  98203. EffectLayer.prototype.hasMesh = function (mesh) {
  98204. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  98205. return true;
  98206. }
  98207. return false;
  98208. };
  98209. /**
  98210. * Returns true if the layer contains information to display, otherwise false.
  98211. * @returns true if the glow layer should be rendered
  98212. */
  98213. EffectLayer.prototype.shouldRender = function () {
  98214. return this.isEnabled && this._shouldRender;
  98215. };
  98216. /**
  98217. * Returns true if the mesh should render, otherwise false.
  98218. * @param mesh The mesh to render
  98219. * @returns true if it should render otherwise false
  98220. */
  98221. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  98222. return true;
  98223. };
  98224. /**
  98225. * Returns true if the mesh should render, otherwise false.
  98226. * @param mesh The mesh to render
  98227. * @returns true if it should render otherwise false
  98228. */
  98229. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  98230. return true;
  98231. };
  98232. /**
  98233. * Renders the submesh passed in parameter to the generation map.
  98234. */
  98235. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  98236. var _this = this;
  98237. if (!this.shouldRender()) {
  98238. return;
  98239. }
  98240. var material = subMesh.getMaterial();
  98241. var mesh = subMesh.getRenderingMesh();
  98242. var scene = this._scene;
  98243. var engine = scene.getEngine();
  98244. if (!material) {
  98245. return;
  98246. }
  98247. // Do not block in blend mode.
  98248. if (material.needAlphaBlendingForMesh(mesh)) {
  98249. return;
  98250. }
  98251. // Culling
  98252. engine.setState(material.backFaceCulling);
  98253. // Managing instances
  98254. var batch = mesh._getInstancesRenderList(subMesh._id);
  98255. if (batch.mustReturn) {
  98256. return;
  98257. }
  98258. // Early Exit per mesh
  98259. if (!this._shouldRenderMesh(mesh)) {
  98260. return;
  98261. }
  98262. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  98263. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  98264. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  98265. engine.enableEffect(this._effectLayerMapGenerationEffect);
  98266. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  98267. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  98268. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  98269. // Alpha test
  98270. if (material && material.needAlphaTesting()) {
  98271. var alphaTexture = material.getAlphaTestTexture();
  98272. if (alphaTexture) {
  98273. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  98274. var textureMatrix = alphaTexture.getTextureMatrix();
  98275. if (textureMatrix) {
  98276. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  98277. }
  98278. }
  98279. }
  98280. // Glow emissive only
  98281. if (this._emissiveTextureAndColor.texture) {
  98282. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  98283. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  98284. }
  98285. // Bones
  98286. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  98287. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  98288. }
  98289. // Morph targets
  98290. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  98291. // Draw
  98292. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  98293. }
  98294. else {
  98295. // Need to reset refresh rate of the main map
  98296. this._mainTexture.resetRefreshCounter();
  98297. }
  98298. };
  98299. /**
  98300. * Rebuild the required buffers.
  98301. * @hidden Internal use only.
  98302. */
  98303. EffectLayer.prototype._rebuild = function () {
  98304. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98305. if (vb) {
  98306. vb._rebuild();
  98307. }
  98308. this._generateIndexBuffer();
  98309. };
  98310. /**
  98311. * Dispose only the render target textures and post process.
  98312. */
  98313. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  98314. this._mainTexture.dispose();
  98315. for (var i = 0; i < this._postProcesses.length; i++) {
  98316. if (this._postProcesses[i]) {
  98317. this._postProcesses[i].dispose();
  98318. }
  98319. }
  98320. this._postProcesses = [];
  98321. for (var i = 0; i < this._textures.length; i++) {
  98322. if (this._textures[i]) {
  98323. this._textures[i].dispose();
  98324. }
  98325. }
  98326. this._textures = [];
  98327. };
  98328. /**
  98329. * Dispose the highlight layer and free resources.
  98330. */
  98331. EffectLayer.prototype.dispose = function () {
  98332. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98333. if (vertexBuffer) {
  98334. vertexBuffer.dispose();
  98335. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98336. }
  98337. if (this._indexBuffer) {
  98338. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98339. this._indexBuffer = null;
  98340. }
  98341. // Clean textures and post processes
  98342. this._disposeTextureAndPostProcesses();
  98343. // Remove from scene
  98344. var index = this._scene.effectLayers.indexOf(this, 0);
  98345. if (index > -1) {
  98346. this._scene.effectLayers.splice(index, 1);
  98347. }
  98348. // Callback
  98349. this.onDisposeObservable.notifyObservers(this);
  98350. this.onDisposeObservable.clear();
  98351. this.onBeforeRenderMainTextureObservable.clear();
  98352. this.onBeforeComposeObservable.clear();
  98353. this.onAfterComposeObservable.clear();
  98354. this.onSizeChangedObservable.clear();
  98355. };
  98356. /**
  98357. * Gets the class name of the effect layer
  98358. * @returns the string with the class name of the effect layer
  98359. */
  98360. EffectLayer.prototype.getClassName = function () {
  98361. return "EffectLayer";
  98362. };
  98363. /**
  98364. * Creates an effect layer from parsed effect layer data
  98365. * @param parsedEffectLayer defines effect layer data
  98366. * @param scene defines the current scene
  98367. * @param rootUrl defines the root URL containing the effect layer information
  98368. * @returns a parsed effect Layer
  98369. */
  98370. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  98371. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  98372. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  98373. };
  98374. __decorate([
  98375. BABYLON.serialize()
  98376. ], EffectLayer.prototype, "name", void 0);
  98377. __decorate([
  98378. BABYLON.serializeAsColor4()
  98379. ], EffectLayer.prototype, "neutralColor", void 0);
  98380. __decorate([
  98381. BABYLON.serialize()
  98382. ], EffectLayer.prototype, "isEnabled", void 0);
  98383. __decorate([
  98384. BABYLON.serializeAsCameraReference()
  98385. ], EffectLayer.prototype, "camera", null);
  98386. __decorate([
  98387. BABYLON.serialize()
  98388. ], EffectLayer.prototype, "renderingGroupId", null);
  98389. return EffectLayer;
  98390. }());
  98391. BABYLON.EffectLayer = EffectLayer;
  98392. })(BABYLON || (BABYLON = {}));
  98393. //# sourceMappingURL=babylon.effectLayer.js.map
  98394. var BABYLON;
  98395. (function (BABYLON) {
  98396. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  98397. for (var index = 0; index < this.effectLayers.length; index++) {
  98398. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  98399. return this.effectLayers[index];
  98400. }
  98401. }
  98402. return null;
  98403. };
  98404. /**
  98405. * Special Glow Blur post process only blurring the alpha channel
  98406. * It enforces keeping the most luminous color in the color channel.
  98407. */
  98408. var GlowBlurPostProcess = /** @class */ (function (_super) {
  98409. __extends(GlowBlurPostProcess, _super);
  98410. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  98411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  98412. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  98413. _this.direction = direction;
  98414. _this.kernel = kernel;
  98415. _this.onApplyObservable.add(function (effect) {
  98416. effect.setFloat2("screenSize", _this.width, _this.height);
  98417. effect.setVector2("direction", _this.direction);
  98418. effect.setFloat("blurWidth", _this.kernel);
  98419. });
  98420. return _this;
  98421. }
  98422. return GlowBlurPostProcess;
  98423. }(BABYLON.PostProcess));
  98424. /**
  98425. * The highlight layer Helps adding a glow effect around a mesh.
  98426. *
  98427. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98428. * glowy meshes to your scene.
  98429. *
  98430. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  98431. */
  98432. var HighlightLayer = /** @class */ (function (_super) {
  98433. __extends(HighlightLayer, _super);
  98434. /**
  98435. * Instantiates a new highlight Layer and references it to the scene..
  98436. * @param name The name of the layer
  98437. * @param scene The scene to use the layer in
  98438. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  98439. */
  98440. function HighlightLayer(name, scene, options) {
  98441. var _this = _super.call(this, name, scene) || this;
  98442. _this.name = name;
  98443. /**
  98444. * Specifies whether or not the inner glow is ACTIVE in the layer.
  98445. */
  98446. _this.innerGlow = true;
  98447. /**
  98448. * Specifies whether or not the outer glow is ACTIVE in the layer.
  98449. */
  98450. _this.outerGlow = true;
  98451. /**
  98452. * An event triggered when the highlight layer is being blurred.
  98453. */
  98454. _this.onBeforeBlurObservable = new BABYLON.Observable();
  98455. /**
  98456. * An event triggered when the highlight layer has been blurred.
  98457. */
  98458. _this.onAfterBlurObservable = new BABYLON.Observable();
  98459. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  98460. _this._meshes = {};
  98461. _this._excludedMeshes = {};
  98462. _this.neutralColor = HighlightLayer.NeutralColor;
  98463. // Warn on stencil
  98464. if (!_this._engine.isStencilEnable) {
  98465. 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 }");
  98466. }
  98467. // Adapt options
  98468. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  98469. // Initialize the layer
  98470. _this._init({
  98471. alphaBlendingMode: _this._options.alphaBlendingMode,
  98472. camera: _this._options.camera,
  98473. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98474. mainTextureRatio: _this._options.mainTextureRatio,
  98475. renderingGroupId: _this._options.renderingGroupId
  98476. });
  98477. // Do not render as long as no meshes have been added
  98478. _this._shouldRender = false;
  98479. return _this;
  98480. }
  98481. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  98482. /**
  98483. * Gets the horizontal size of the blur.
  98484. */
  98485. get: function () {
  98486. return this._horizontalBlurPostprocess.kernel;
  98487. },
  98488. /**
  98489. * Specifies the horizontal size of the blur.
  98490. */
  98491. set: function (value) {
  98492. this._horizontalBlurPostprocess.kernel = value;
  98493. },
  98494. enumerable: true,
  98495. configurable: true
  98496. });
  98497. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  98498. /**
  98499. * Gets the vertical size of the blur.
  98500. */
  98501. get: function () {
  98502. return this._verticalBlurPostprocess.kernel;
  98503. },
  98504. /**
  98505. * Specifies the vertical size of the blur.
  98506. */
  98507. set: function (value) {
  98508. this._verticalBlurPostprocess.kernel = value;
  98509. },
  98510. enumerable: true,
  98511. configurable: true
  98512. });
  98513. /**
  98514. * Get the effect name of the layer.
  98515. * @return The effect name
  98516. */
  98517. HighlightLayer.prototype.getEffectName = function () {
  98518. return HighlightLayer.EffectName;
  98519. };
  98520. /**
  98521. * Create the merge effect. This is the shader use to blit the information back
  98522. * to the main canvas at the end of the scene rendering.
  98523. */
  98524. HighlightLayer.prototype._createMergeEffect = function () {
  98525. // Effect
  98526. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  98527. };
  98528. /**
  98529. * Creates the render target textures and post processes used in the highlight layer.
  98530. */
  98531. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  98532. var _this = this;
  98533. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  98534. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  98535. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98536. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98537. var textureType = 0;
  98538. if (this._engine.getCaps().textureHalfFloatRender) {
  98539. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98540. }
  98541. else {
  98542. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98543. }
  98544. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  98545. width: blurTextureWidth,
  98546. height: blurTextureHeight
  98547. }, this._scene, false, true, textureType);
  98548. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98549. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98550. this._blurTexture.anisotropicFilteringLevel = 16;
  98551. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  98552. this._blurTexture.renderParticles = false;
  98553. this._blurTexture.ignoreCameraViewport = true;
  98554. this._textures = [this._blurTexture];
  98555. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  98556. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98557. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  98558. effect.setTexture("textureSampler", _this._mainTexture);
  98559. });
  98560. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98561. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98562. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  98563. });
  98564. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98565. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  98566. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  98567. });
  98568. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98569. }
  98570. else {
  98571. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  98572. width: blurTextureWidth,
  98573. height: blurTextureHeight
  98574. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98575. this._horizontalBlurPostprocess.width = blurTextureWidth;
  98576. this._horizontalBlurPostprocess.height = blurTextureHeight;
  98577. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98578. effect.setTexture("textureSampler", _this._mainTexture);
  98579. });
  98580. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  98581. width: blurTextureWidth,
  98582. height: blurTextureHeight
  98583. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98584. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98585. }
  98586. this._mainTexture.onAfterUnbindObservable.add(function () {
  98587. _this.onBeforeBlurObservable.notifyObservers(_this);
  98588. var internalTexture = _this._blurTexture.getInternalTexture();
  98589. if (internalTexture) {
  98590. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  98591. }
  98592. _this.onAfterBlurObservable.notifyObservers(_this);
  98593. });
  98594. // Prevent autoClear.
  98595. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98596. };
  98597. /**
  98598. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98599. */
  98600. HighlightLayer.prototype.needStencil = function () {
  98601. return true;
  98602. };
  98603. /**
  98604. * Checks for the readiness of the element composing the layer.
  98605. * @param subMesh the mesh to check for
  98606. * @param useInstances specify wether or not to use instances to render the mesh
  98607. * @param emissiveTexture the associated emissive texture used to generate the glow
  98608. * @return true if ready otherwise, false
  98609. */
  98610. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  98611. var material = subMesh.getMaterial();
  98612. var mesh = subMesh.getRenderingMesh();
  98613. if (!material || !mesh || !this._meshes) {
  98614. return false;
  98615. }
  98616. var emissiveTexture = null;
  98617. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98618. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98619. emissiveTexture = material.emissiveTexture;
  98620. }
  98621. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98622. };
  98623. /**
  98624. * Implementation specific of rendering the generating effect on the main canvas.
  98625. * @param effect The effect used to render through
  98626. */
  98627. HighlightLayer.prototype._internalRender = function (effect) {
  98628. // Texture
  98629. effect.setTexture("textureSampler", this._blurTexture);
  98630. // Cache
  98631. var engine = this._engine;
  98632. var previousStencilBuffer = engine.getStencilBuffer();
  98633. var previousStencilFunction = engine.getStencilFunction();
  98634. var previousStencilMask = engine.getStencilMask();
  98635. var previousStencilOperationPass = engine.getStencilOperationPass();
  98636. var previousStencilOperationFail = engine.getStencilOperationFail();
  98637. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  98638. var previousStencilReference = engine.getStencilFunctionReference();
  98639. // Stencil operations
  98640. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  98641. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  98642. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  98643. // Draw order
  98644. engine.setStencilMask(0x00);
  98645. engine.setStencilBuffer(true);
  98646. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  98647. // 2 passes inner outer
  98648. if (this.outerGlow) {
  98649. effect.setFloat("offset", 0);
  98650. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  98651. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98652. }
  98653. if (this.innerGlow) {
  98654. effect.setFloat("offset", 1);
  98655. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  98656. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98657. }
  98658. // Restore Cache
  98659. engine.setStencilFunction(previousStencilFunction);
  98660. engine.setStencilMask(previousStencilMask);
  98661. engine.setStencilBuffer(previousStencilBuffer);
  98662. engine.setStencilOperationPass(previousStencilOperationPass);
  98663. engine.setStencilOperationFail(previousStencilOperationFail);
  98664. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  98665. engine.setStencilFunctionReference(previousStencilReference);
  98666. };
  98667. /**
  98668. * Returns true if the layer contains information to display, otherwise false.
  98669. */
  98670. HighlightLayer.prototype.shouldRender = function () {
  98671. if (_super.prototype.shouldRender.call(this)) {
  98672. return this._meshes ? true : false;
  98673. }
  98674. return false;
  98675. };
  98676. /**
  98677. * Returns true if the mesh should render, otherwise false.
  98678. * @param mesh The mesh to render
  98679. * @returns true if it should render otherwise false
  98680. */
  98681. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  98682. // Excluded Mesh
  98683. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  98684. return false;
  98685. }
  98686. ;
  98687. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98688. return false;
  98689. }
  98690. return true;
  98691. };
  98692. /**
  98693. * Sets the required values for both the emissive texture and and the main color.
  98694. */
  98695. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98696. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98697. if (highlightLayerMesh) {
  98698. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  98699. }
  98700. else {
  98701. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98702. }
  98703. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98704. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98705. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  98706. }
  98707. else {
  98708. this._emissiveTextureAndColor.texture = null;
  98709. }
  98710. };
  98711. /**
  98712. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  98713. * @param mesh The mesh to exclude from the highlight layer
  98714. */
  98715. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  98716. if (!this._excludedMeshes) {
  98717. return;
  98718. }
  98719. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98720. if (!meshExcluded) {
  98721. this._excludedMeshes[mesh.uniqueId] = {
  98722. mesh: mesh,
  98723. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  98724. mesh.getEngine().setStencilBuffer(false);
  98725. }),
  98726. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  98727. mesh.getEngine().setStencilBuffer(true);
  98728. }),
  98729. };
  98730. }
  98731. };
  98732. /**
  98733. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  98734. * @param mesh The mesh to highlight
  98735. */
  98736. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  98737. if (!this._excludedMeshes) {
  98738. return;
  98739. }
  98740. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98741. if (meshExcluded) {
  98742. if (meshExcluded.beforeRender) {
  98743. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  98744. }
  98745. if (meshExcluded.afterRender) {
  98746. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  98747. }
  98748. }
  98749. this._excludedMeshes[mesh.uniqueId] = null;
  98750. };
  98751. /**
  98752. * Determine if a given mesh will be highlighted by the current HighlightLayer
  98753. * @param mesh mesh to test
  98754. * @returns true if the mesh will be highlighted by the current HighlightLayer
  98755. */
  98756. HighlightLayer.prototype.hasMesh = function (mesh) {
  98757. if (!this._meshes) {
  98758. return false;
  98759. }
  98760. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98761. return false;
  98762. }
  98763. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  98764. };
  98765. /**
  98766. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  98767. * @param mesh The mesh to highlight
  98768. * @param color The color of the highlight
  98769. * @param glowEmissiveOnly Extract the glow from the emissive texture
  98770. */
  98771. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  98772. var _this = this;
  98773. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  98774. if (!this._meshes) {
  98775. return;
  98776. }
  98777. var meshHighlight = this._meshes[mesh.uniqueId];
  98778. if (meshHighlight) {
  98779. meshHighlight.color = color;
  98780. }
  98781. else {
  98782. this._meshes[mesh.uniqueId] = {
  98783. mesh: mesh,
  98784. color: color,
  98785. // Lambda required for capture due to Observable this context
  98786. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  98787. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  98788. _this._defaultStencilReference(mesh);
  98789. }
  98790. else {
  98791. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  98792. }
  98793. }),
  98794. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  98795. glowEmissiveOnly: glowEmissiveOnly
  98796. };
  98797. mesh.onDisposeObservable.add(function () {
  98798. _this._disposeMesh(mesh);
  98799. });
  98800. }
  98801. this._shouldRender = true;
  98802. };
  98803. /**
  98804. * Remove a mesh from the highlight layer in order to make it stop glowing.
  98805. * @param mesh The mesh to highlight
  98806. */
  98807. HighlightLayer.prototype.removeMesh = function (mesh) {
  98808. if (!this._meshes) {
  98809. return;
  98810. }
  98811. var meshHighlight = this._meshes[mesh.uniqueId];
  98812. if (meshHighlight) {
  98813. if (meshHighlight.observerHighlight) {
  98814. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98815. }
  98816. if (meshHighlight.observerDefault) {
  98817. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98818. }
  98819. delete this._meshes[mesh.uniqueId];
  98820. }
  98821. this._shouldRender = false;
  98822. for (var meshHighlightToCheck in this._meshes) {
  98823. if (this._meshes[meshHighlightToCheck]) {
  98824. this._shouldRender = true;
  98825. break;
  98826. }
  98827. }
  98828. };
  98829. /**
  98830. * Force the stencil to the normal expected value for none glowing parts
  98831. */
  98832. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  98833. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  98834. };
  98835. /**
  98836. * Free any resources and references associated to a mesh.
  98837. * Internal use
  98838. * @param mesh The mesh to free.
  98839. */
  98840. HighlightLayer.prototype._disposeMesh = function (mesh) {
  98841. this.removeMesh(mesh);
  98842. this.removeExcludedMesh(mesh);
  98843. };
  98844. /**
  98845. * Dispose the highlight layer and free resources.
  98846. */
  98847. HighlightLayer.prototype.dispose = function () {
  98848. if (this._meshes) {
  98849. // Clean mesh references
  98850. for (var id in this._meshes) {
  98851. var meshHighlight = this._meshes[id];
  98852. if (meshHighlight && meshHighlight.mesh) {
  98853. if (meshHighlight.observerHighlight) {
  98854. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98855. }
  98856. if (meshHighlight.observerDefault) {
  98857. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98858. }
  98859. }
  98860. }
  98861. this._meshes = null;
  98862. }
  98863. if (this._excludedMeshes) {
  98864. for (var id in this._excludedMeshes) {
  98865. var meshHighlight = this._excludedMeshes[id];
  98866. if (meshHighlight) {
  98867. if (meshHighlight.beforeRender) {
  98868. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  98869. }
  98870. if (meshHighlight.afterRender) {
  98871. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  98872. }
  98873. }
  98874. }
  98875. this._excludedMeshes = null;
  98876. }
  98877. _super.prototype.dispose.call(this);
  98878. };
  98879. /**
  98880. * Gets the class name of the effect layer
  98881. * @returns the string with the class name of the effect layer
  98882. */
  98883. HighlightLayer.prototype.getClassName = function () {
  98884. return "HighlightLayer";
  98885. };
  98886. /**
  98887. * Serializes this Highlight layer
  98888. * @returns a serialized Highlight layer object
  98889. */
  98890. HighlightLayer.prototype.serialize = function () {
  98891. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98892. serializationObject.customType = "BABYLON.HighlightLayer";
  98893. // Highlighted meshes
  98894. serializationObject.meshes = [];
  98895. if (this._meshes) {
  98896. for (var m in this._meshes) {
  98897. var mesh = this._meshes[m];
  98898. if (mesh) {
  98899. serializationObject.meshes.push({
  98900. glowEmissiveOnly: mesh.glowEmissiveOnly,
  98901. color: mesh.color.asArray(),
  98902. meshId: mesh.mesh.id
  98903. });
  98904. }
  98905. }
  98906. }
  98907. // Excluded meshes
  98908. serializationObject.excludedMeshes = [];
  98909. if (this._excludedMeshes) {
  98910. for (var e in this._excludedMeshes) {
  98911. var excludedMesh = this._excludedMeshes[e];
  98912. if (excludedMesh) {
  98913. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  98914. }
  98915. }
  98916. }
  98917. return serializationObject;
  98918. };
  98919. /**
  98920. * Creates a Highlight layer from parsed Highlight layer data
  98921. * @param parsedHightlightLayer defines the Highlight layer data
  98922. * @param scene defines the current scene
  98923. * @param rootUrl defines the root URL containing the Highlight layer information
  98924. * @returns a parsed Highlight layer
  98925. */
  98926. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  98927. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  98928. var index;
  98929. // Excluded meshes
  98930. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  98931. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  98932. if (mesh) {
  98933. hl.addExcludedMesh(mesh);
  98934. }
  98935. }
  98936. // Included meshes
  98937. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  98938. var highlightedMesh = parsedHightlightLayer.meshes[index];
  98939. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  98940. if (mesh) {
  98941. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  98942. }
  98943. }
  98944. return hl;
  98945. };
  98946. /**
  98947. * Effect Name of the highlight layer.
  98948. */
  98949. HighlightLayer.EffectName = "HighlightLayer";
  98950. /**
  98951. * The neutral color used during the preparation of the glow effect.
  98952. * This is black by default as the blend operation is a blend operation.
  98953. */
  98954. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  98955. /**
  98956. * Stencil value used for glowing meshes.
  98957. */
  98958. HighlightLayer.GlowingMeshStencilReference = 0x02;
  98959. /**
  98960. * Stencil value used for the other meshes in the scene.
  98961. */
  98962. HighlightLayer.NormalMeshStencilReference = 0x01;
  98963. __decorate([
  98964. BABYLON.serialize()
  98965. ], HighlightLayer.prototype, "innerGlow", void 0);
  98966. __decorate([
  98967. BABYLON.serialize()
  98968. ], HighlightLayer.prototype, "outerGlow", void 0);
  98969. __decorate([
  98970. BABYLON.serialize()
  98971. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  98972. __decorate([
  98973. BABYLON.serialize()
  98974. ], HighlightLayer.prototype, "blurVerticalSize", null);
  98975. __decorate([
  98976. BABYLON.serialize("options")
  98977. ], HighlightLayer.prototype, "_options", void 0);
  98978. return HighlightLayer;
  98979. }(BABYLON.EffectLayer));
  98980. BABYLON.HighlightLayer = HighlightLayer;
  98981. })(BABYLON || (BABYLON = {}));
  98982. //# sourceMappingURL=babylon.highlightLayer.js.map
  98983. var BABYLON;
  98984. (function (BABYLON) {
  98985. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  98986. for (var index = 0; index < this.effectLayers.length; index++) {
  98987. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  98988. return this.effectLayers[index];
  98989. }
  98990. }
  98991. return null;
  98992. };
  98993. /**
  98994. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  98995. *
  98996. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98997. * glowy meshes to your scene.
  98998. *
  98999. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  99000. */
  99001. var GlowLayer = /** @class */ (function (_super) {
  99002. __extends(GlowLayer, _super);
  99003. /**
  99004. * Instantiates a new glow Layer and references it to the scene.
  99005. * @param name The name of the layer
  99006. * @param scene The scene to use the layer in
  99007. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  99008. */
  99009. function GlowLayer(name, scene, options) {
  99010. var _this = _super.call(this, name, scene) || this;
  99011. _this._intensity = 1.0;
  99012. _this._includedOnlyMeshes = [];
  99013. _this._excludedMeshes = [];
  99014. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  99015. // Adapt options
  99016. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  99017. // Initialize the layer
  99018. _this._init({
  99019. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  99020. camera: _this._options.camera,
  99021. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  99022. mainTextureRatio: _this._options.mainTextureRatio,
  99023. renderingGroupId: _this._options.renderingGroupId
  99024. });
  99025. return _this;
  99026. }
  99027. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  99028. /**
  99029. * Gets the kernel size of the blur.
  99030. */
  99031. get: function () {
  99032. return this._horizontalBlurPostprocess1.kernel;
  99033. },
  99034. /**
  99035. * Sets the kernel size of the blur.
  99036. */
  99037. set: function (value) {
  99038. this._horizontalBlurPostprocess1.kernel = value;
  99039. this._verticalBlurPostprocess1.kernel = value;
  99040. this._horizontalBlurPostprocess2.kernel = value;
  99041. this._verticalBlurPostprocess2.kernel = value;
  99042. },
  99043. enumerable: true,
  99044. configurable: true
  99045. });
  99046. Object.defineProperty(GlowLayer.prototype, "intensity", {
  99047. /**
  99048. * Gets the glow intensity.
  99049. */
  99050. get: function () {
  99051. return this._intensity;
  99052. },
  99053. /**
  99054. * Sets the glow intensity.
  99055. */
  99056. set: function (value) {
  99057. this._intensity = value;
  99058. },
  99059. enumerable: true,
  99060. configurable: true
  99061. });
  99062. /**
  99063. * Get the effect name of the layer.
  99064. * @return The effect name
  99065. */
  99066. GlowLayer.prototype.getEffectName = function () {
  99067. return GlowLayer.EffectName;
  99068. };
  99069. /**
  99070. * Create the merge effect. This is the shader use to blit the information back
  99071. * to the main canvas at the end of the scene rendering.
  99072. */
  99073. GlowLayer.prototype._createMergeEffect = function () {
  99074. // Effect
  99075. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  99076. };
  99077. /**
  99078. * Creates the render target textures and post processes used in the glow layer.
  99079. */
  99080. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  99081. var _this = this;
  99082. var blurTextureWidth = this._mainTextureDesiredSize.width;
  99083. var blurTextureHeight = this._mainTextureDesiredSize.height;
  99084. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  99085. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  99086. var textureType = 0;
  99087. if (this._engine.getCaps().textureHalfFloatRender) {
  99088. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99089. }
  99090. else {
  99091. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99092. }
  99093. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  99094. width: blurTextureWidth,
  99095. height: blurTextureHeight
  99096. }, this._scene, false, true, textureType);
  99097. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99098. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99099. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99100. this._blurTexture1.renderParticles = false;
  99101. this._blurTexture1.ignoreCameraViewport = true;
  99102. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  99103. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  99104. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  99105. width: blurTextureWidth2,
  99106. height: blurTextureHeight2
  99107. }, this._scene, false, true, textureType);
  99108. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99109. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99110. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99111. this._blurTexture2.renderParticles = false;
  99112. this._blurTexture2.ignoreCameraViewport = true;
  99113. this._textures = [this._blurTexture1, this._blurTexture2];
  99114. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  99115. width: blurTextureWidth,
  99116. height: blurTextureHeight
  99117. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99118. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  99119. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  99120. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  99121. effect.setTexture("textureSampler", _this._mainTexture);
  99122. });
  99123. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  99124. width: blurTextureWidth,
  99125. height: blurTextureHeight
  99126. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99127. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  99128. width: blurTextureWidth2,
  99129. height: blurTextureHeight2
  99130. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99131. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  99132. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  99133. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  99134. effect.setTexture("textureSampler", _this._blurTexture1);
  99135. });
  99136. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  99137. width: blurTextureWidth2,
  99138. height: blurTextureHeight2
  99139. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99140. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  99141. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  99142. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  99143. this._mainTexture.samples = this._options.mainTextureSamples;
  99144. this._mainTexture.onAfterUnbindObservable.add(function () {
  99145. var internalTexture = _this._blurTexture1.getInternalTexture();
  99146. if (internalTexture) {
  99147. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  99148. internalTexture = _this._blurTexture2.getInternalTexture();
  99149. if (internalTexture) {
  99150. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  99151. }
  99152. }
  99153. });
  99154. // Prevent autoClear.
  99155. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  99156. };
  99157. /**
  99158. * Checks for the readiness of the element composing the layer.
  99159. * @param subMesh the mesh to check for
  99160. * @param useInstances specify wether or not to use instances to render the mesh
  99161. * @param emissiveTexture the associated emissive texture used to generate the glow
  99162. * @return true if ready otherwise, false
  99163. */
  99164. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  99165. var material = subMesh.getMaterial();
  99166. var mesh = subMesh.getRenderingMesh();
  99167. if (!material || !mesh) {
  99168. return false;
  99169. }
  99170. var emissiveTexture = material.emissiveTexture;
  99171. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  99172. };
  99173. /**
  99174. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  99175. */
  99176. GlowLayer.prototype.needStencil = function () {
  99177. return false;
  99178. };
  99179. /**
  99180. * Implementation specific of rendering the generating effect on the main canvas.
  99181. * @param effect The effect used to render through
  99182. */
  99183. GlowLayer.prototype._internalRender = function (effect) {
  99184. // Texture
  99185. effect.setTexture("textureSampler", this._blurTexture1);
  99186. effect.setTexture("textureSampler2", this._blurTexture2);
  99187. effect.setFloat("offset", this._intensity);
  99188. // Cache
  99189. var engine = this._engine;
  99190. var previousStencilBuffer = engine.getStencilBuffer();
  99191. // Draw order
  99192. engine.setStencilBuffer(false);
  99193. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99194. // Draw order
  99195. engine.setStencilBuffer(previousStencilBuffer);
  99196. };
  99197. /**
  99198. * Sets the required values for both the emissive texture and and the main color.
  99199. */
  99200. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  99201. var textureLevel = 1.0;
  99202. if (this.customEmissiveTextureSelector) {
  99203. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  99204. }
  99205. else {
  99206. if (material) {
  99207. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  99208. if (this._emissiveTextureAndColor.texture) {
  99209. textureLevel = this._emissiveTextureAndColor.texture.level;
  99210. }
  99211. }
  99212. else {
  99213. this._emissiveTextureAndColor.texture = null;
  99214. }
  99215. }
  99216. if (this.customEmissiveColorSelector) {
  99217. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  99218. }
  99219. else {
  99220. if (material.emissiveColor) {
  99221. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  99222. }
  99223. else {
  99224. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  99225. }
  99226. }
  99227. };
  99228. /**
  99229. * Returns true if the mesh should render, otherwise false.
  99230. * @param mesh The mesh to render
  99231. * @returns true if it should render otherwise false
  99232. */
  99233. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  99234. return this.hasMesh(mesh);
  99235. };
  99236. /**
  99237. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  99238. * @param mesh The mesh to exclude from the glow layer
  99239. */
  99240. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  99241. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  99242. this._excludedMeshes.push(mesh.uniqueId);
  99243. }
  99244. };
  99245. /**
  99246. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  99247. * @param mesh The mesh to remove
  99248. */
  99249. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  99250. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  99251. if (index !== -1) {
  99252. this._excludedMeshes.splice(index, 1);
  99253. }
  99254. };
  99255. /**
  99256. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  99257. * @param mesh The mesh to include in the glow layer
  99258. */
  99259. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  99260. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  99261. this._includedOnlyMeshes.push(mesh.uniqueId);
  99262. }
  99263. };
  99264. /**
  99265. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  99266. * @param mesh The mesh to remove
  99267. */
  99268. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  99269. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  99270. if (index !== -1) {
  99271. this._includedOnlyMeshes.splice(index, 1);
  99272. }
  99273. };
  99274. /**
  99275. * Determine if a given mesh will be used in the glow layer
  99276. * @param mesh The mesh to test
  99277. * @returns true if the mesh will be highlighted by the current glow layer
  99278. */
  99279. GlowLayer.prototype.hasMesh = function (mesh) {
  99280. if (!_super.prototype.hasMesh.call(this, mesh)) {
  99281. return false;
  99282. }
  99283. // Included Mesh
  99284. if (this._includedOnlyMeshes.length) {
  99285. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  99286. }
  99287. ;
  99288. // Excluded Mesh
  99289. if (this._excludedMeshes.length) {
  99290. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  99291. }
  99292. ;
  99293. return true;
  99294. };
  99295. /**
  99296. * Free any resources and references associated to a mesh.
  99297. * Internal use
  99298. * @param mesh The mesh to free.
  99299. */
  99300. GlowLayer.prototype._disposeMesh = function (mesh) {
  99301. this.removeIncludedOnlyMesh(mesh);
  99302. this.removeExcludedMesh(mesh);
  99303. };
  99304. /**
  99305. * Gets the class name of the effect layer
  99306. * @returns the string with the class name of the effect layer
  99307. */
  99308. GlowLayer.prototype.getClassName = function () {
  99309. return "GlowLayer";
  99310. };
  99311. /**
  99312. * Serializes this glow layer
  99313. * @returns a serialized glow layer object
  99314. */
  99315. GlowLayer.prototype.serialize = function () {
  99316. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99317. serializationObject.customType = "BABYLON.GlowLayer";
  99318. var index;
  99319. // Included meshes
  99320. serializationObject.includedMeshes = [];
  99321. if (this._includedOnlyMeshes.length) {
  99322. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  99323. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  99324. if (mesh) {
  99325. serializationObject.includedMeshes.push(mesh.id);
  99326. }
  99327. }
  99328. }
  99329. // Excluded meshes
  99330. serializationObject.excludedMeshes = [];
  99331. if (this._excludedMeshes.length) {
  99332. for (index = 0; index < this._excludedMeshes.length; index++) {
  99333. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  99334. if (mesh) {
  99335. serializationObject.excludedMeshes.push(mesh.id);
  99336. }
  99337. }
  99338. }
  99339. return serializationObject;
  99340. };
  99341. /**
  99342. * Creates a Glow Layer from parsed glow layer data
  99343. * @param parsedGlowLayer defines glow layer data
  99344. * @param scene defines the current scene
  99345. * @param rootUrl defines the root URL containing the glow layer information
  99346. * @returns a parsed Glow Layer
  99347. */
  99348. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  99349. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  99350. var index;
  99351. // Excluded meshes
  99352. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  99353. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  99354. if (mesh) {
  99355. gl.addExcludedMesh(mesh);
  99356. }
  99357. }
  99358. // Included meshes
  99359. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  99360. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  99361. if (mesh) {
  99362. gl.addIncludedOnlyMesh(mesh);
  99363. }
  99364. }
  99365. return gl;
  99366. };
  99367. /**
  99368. * Effect Name of the layer.
  99369. */
  99370. GlowLayer.EffectName = "GlowLayer";
  99371. /**
  99372. * The default blur kernel size used for the glow.
  99373. */
  99374. GlowLayer.DefaultBlurKernelSize = 32;
  99375. /**
  99376. * The default texture size ratio used for the glow.
  99377. */
  99378. GlowLayer.DefaultTextureRatio = 0.5;
  99379. __decorate([
  99380. BABYLON.serialize()
  99381. ], GlowLayer.prototype, "blurKernelSize", null);
  99382. __decorate([
  99383. BABYLON.serialize()
  99384. ], GlowLayer.prototype, "intensity", null);
  99385. __decorate([
  99386. BABYLON.serialize("options")
  99387. ], GlowLayer.prototype, "_options", void 0);
  99388. return GlowLayer;
  99389. }(BABYLON.EffectLayer));
  99390. BABYLON.GlowLayer = GlowLayer;
  99391. })(BABYLON || (BABYLON = {}));
  99392. //# sourceMappingURL=babylon.glowLayer.js.map
  99393. var BABYLON;
  99394. (function (BABYLON) {
  99395. /**
  99396. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  99397. */
  99398. var AssetTaskState;
  99399. (function (AssetTaskState) {
  99400. /**
  99401. * Initialization
  99402. */
  99403. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  99404. /**
  99405. * Running
  99406. */
  99407. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  99408. /**
  99409. * Done
  99410. */
  99411. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  99412. /**
  99413. * Error
  99414. */
  99415. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  99416. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  99417. /**
  99418. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  99419. */
  99420. var AbstractAssetTask = /** @class */ (function () {
  99421. /**
  99422. * Creates a new {BABYLON.AssetsManager}
  99423. * @param name defines the name of the task
  99424. */
  99425. function AbstractAssetTask(
  99426. /**
  99427. * Task name
  99428. */ name) {
  99429. this.name = name;
  99430. this._isCompleted = false;
  99431. this._taskState = AssetTaskState.INIT;
  99432. }
  99433. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  99434. /**
  99435. * Get if the task is completed
  99436. */
  99437. get: function () {
  99438. return this._isCompleted;
  99439. },
  99440. enumerable: true,
  99441. configurable: true
  99442. });
  99443. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  99444. /**
  99445. * Gets the current state of the task
  99446. */
  99447. get: function () {
  99448. return this._taskState;
  99449. },
  99450. enumerable: true,
  99451. configurable: true
  99452. });
  99453. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  99454. /**
  99455. * Gets the current error object (if task is in error)
  99456. */
  99457. get: function () {
  99458. return this._errorObject;
  99459. },
  99460. enumerable: true,
  99461. configurable: true
  99462. });
  99463. /**
  99464. * Internal only
  99465. * @hidden
  99466. */
  99467. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  99468. if (this._errorObject) {
  99469. return;
  99470. }
  99471. this._errorObject = {
  99472. message: message,
  99473. exception: exception
  99474. };
  99475. };
  99476. /**
  99477. * Execute the current task
  99478. * @param scene defines the scene where you want your assets to be loaded
  99479. * @param onSuccess is a callback called when the task is successfully executed
  99480. * @param onError is a callback called if an error occurs
  99481. */
  99482. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99483. var _this = this;
  99484. this._taskState = AssetTaskState.RUNNING;
  99485. this.runTask(scene, function () {
  99486. _this.onDoneCallback(onSuccess, onError);
  99487. }, function (msg, exception) {
  99488. _this.onErrorCallback(onError, msg, exception);
  99489. });
  99490. };
  99491. /**
  99492. * Execute the current task
  99493. * @param scene defines the scene where you want your assets to be loaded
  99494. * @param onSuccess is a callback called when the task is successfully executed
  99495. * @param onError is a callback called if an error occurs
  99496. */
  99497. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99498. throw new Error("runTask is not implemented");
  99499. };
  99500. /**
  99501. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  99502. * This can be used with failed tasks that have the reason for failure fixed.
  99503. */
  99504. AbstractAssetTask.prototype.reset = function () {
  99505. this._taskState = AssetTaskState.INIT;
  99506. };
  99507. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  99508. this._taskState = AssetTaskState.ERROR;
  99509. this._errorObject = {
  99510. message: message,
  99511. exception: exception
  99512. };
  99513. if (this.onError) {
  99514. this.onError(this, message, exception);
  99515. }
  99516. onError();
  99517. };
  99518. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  99519. try {
  99520. this._taskState = AssetTaskState.DONE;
  99521. this._isCompleted = true;
  99522. if (this.onSuccess) {
  99523. this.onSuccess(this);
  99524. }
  99525. onSuccess();
  99526. }
  99527. catch (e) {
  99528. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  99529. }
  99530. };
  99531. return AbstractAssetTask;
  99532. }());
  99533. BABYLON.AbstractAssetTask = AbstractAssetTask;
  99534. /**
  99535. * Class used to share progress information about assets loading
  99536. */
  99537. var AssetsProgressEvent = /** @class */ (function () {
  99538. /**
  99539. * Creates a {BABYLON.AssetsProgressEvent}
  99540. * @param remainingCount defines the number of remaining tasks to process
  99541. * @param totalCount defines the total number of tasks
  99542. * @param task defines the task that was just processed
  99543. */
  99544. function AssetsProgressEvent(remainingCount, totalCount, task) {
  99545. this.remainingCount = remainingCount;
  99546. this.totalCount = totalCount;
  99547. this.task = task;
  99548. }
  99549. return AssetsProgressEvent;
  99550. }());
  99551. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  99552. /**
  99553. * Define a task used by {BABYLON.AssetsManager} to load meshes
  99554. */
  99555. var MeshAssetTask = /** @class */ (function (_super) {
  99556. __extends(MeshAssetTask, _super);
  99557. /**
  99558. * Creates a new {BABYLON.MeshAssetTask}
  99559. * @param name defines the name of the task
  99560. * @param meshesNames defines the list of mesh's names you want to load
  99561. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  99562. * @param sceneFilename defines the filename of the scene to load from
  99563. */
  99564. function MeshAssetTask(
  99565. /**
  99566. * Defines the name of the task
  99567. */
  99568. name,
  99569. /**
  99570. * Defines the list of mesh's names you want to load
  99571. */
  99572. meshesNames,
  99573. /**
  99574. * Defines the root url to use as a base to load your meshes and associated resources
  99575. */
  99576. rootUrl,
  99577. /**
  99578. * Defines the filename of the scene to load from
  99579. */
  99580. sceneFilename) {
  99581. var _this = _super.call(this, name) || this;
  99582. _this.name = name;
  99583. _this.meshesNames = meshesNames;
  99584. _this.rootUrl = rootUrl;
  99585. _this.sceneFilename = sceneFilename;
  99586. return _this;
  99587. }
  99588. /**
  99589. * Execute the current task
  99590. * @param scene defines the scene where you want your assets to be loaded
  99591. * @param onSuccess is a callback called when the task is successfully executed
  99592. * @param onError is a callback called if an error occurs
  99593. */
  99594. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99595. var _this = this;
  99596. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  99597. _this.loadedMeshes = meshes;
  99598. _this.loadedParticleSystems = particleSystems;
  99599. _this.loadedSkeletons = skeletons;
  99600. onSuccess();
  99601. }, null, function (scene, message, exception) {
  99602. onError(message, exception);
  99603. });
  99604. };
  99605. return MeshAssetTask;
  99606. }(AbstractAssetTask));
  99607. BABYLON.MeshAssetTask = MeshAssetTask;
  99608. /**
  99609. * Define a task used by {BABYLON.AssetsManager} to load text content
  99610. */
  99611. var TextFileAssetTask = /** @class */ (function (_super) {
  99612. __extends(TextFileAssetTask, _super);
  99613. /**
  99614. * Creates a new TextFileAssetTask object
  99615. * @param name defines the name of the task
  99616. * @param url defines the location of the file to load
  99617. */
  99618. function TextFileAssetTask(
  99619. /**
  99620. * Defines the name of the task
  99621. */
  99622. name,
  99623. /**
  99624. * Defines the location of the file to load
  99625. */
  99626. url) {
  99627. var _this = _super.call(this, name) || this;
  99628. _this.name = name;
  99629. _this.url = url;
  99630. return _this;
  99631. }
  99632. /**
  99633. * Execute the current task
  99634. * @param scene defines the scene where you want your assets to be loaded
  99635. * @param onSuccess is a callback called when the task is successfully executed
  99636. * @param onError is a callback called if an error occurs
  99637. */
  99638. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99639. var _this = this;
  99640. scene._loadFile(this.url, function (data) {
  99641. _this.text = data;
  99642. onSuccess();
  99643. }, undefined, false, false, function (request, exception) {
  99644. if (request) {
  99645. onError(request.status + " " + request.statusText, exception);
  99646. }
  99647. });
  99648. };
  99649. return TextFileAssetTask;
  99650. }(AbstractAssetTask));
  99651. BABYLON.TextFileAssetTask = TextFileAssetTask;
  99652. /**
  99653. * Define a task used by {BABYLON.AssetsManager} to load binary data
  99654. */
  99655. var BinaryFileAssetTask = /** @class */ (function (_super) {
  99656. __extends(BinaryFileAssetTask, _super);
  99657. /**
  99658. * Creates a new BinaryFileAssetTask object
  99659. * @param name defines the name of the new task
  99660. * @param url defines the location of the file to load
  99661. */
  99662. function BinaryFileAssetTask(
  99663. /**
  99664. * Defines the name of the task
  99665. */
  99666. name,
  99667. /**
  99668. * Defines the location of the file to load
  99669. */
  99670. url) {
  99671. var _this = _super.call(this, name) || this;
  99672. _this.name = name;
  99673. _this.url = url;
  99674. return _this;
  99675. }
  99676. /**
  99677. * Execute the current task
  99678. * @param scene defines the scene where you want your assets to be loaded
  99679. * @param onSuccess is a callback called when the task is successfully executed
  99680. * @param onError is a callback called if an error occurs
  99681. */
  99682. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99683. var _this = this;
  99684. scene._loadFile(this.url, function (data) {
  99685. _this.data = data;
  99686. onSuccess();
  99687. }, undefined, true, true, function (request, exception) {
  99688. if (request) {
  99689. onError(request.status + " " + request.statusText, exception);
  99690. }
  99691. });
  99692. };
  99693. return BinaryFileAssetTask;
  99694. }(AbstractAssetTask));
  99695. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  99696. /**
  99697. * Define a task used by {BABYLON.AssetsManager} to load images
  99698. */
  99699. var ImageAssetTask = /** @class */ (function (_super) {
  99700. __extends(ImageAssetTask, _super);
  99701. /**
  99702. * Creates a new ImageAssetTask
  99703. * @param name defines the name of the task
  99704. * @param url defines the location of the image to load
  99705. */
  99706. function ImageAssetTask(
  99707. /**
  99708. * Defines the name of the task
  99709. */
  99710. name,
  99711. /**
  99712. * Defines the location of the image to load
  99713. */
  99714. url) {
  99715. var _this = _super.call(this, name) || this;
  99716. _this.name = name;
  99717. _this.url = url;
  99718. return _this;
  99719. }
  99720. /**
  99721. * Execute the current task
  99722. * @param scene defines the scene where you want your assets to be loaded
  99723. * @param onSuccess is a callback called when the task is successfully executed
  99724. * @param onError is a callback called if an error occurs
  99725. */
  99726. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99727. var _this = this;
  99728. var img = new Image();
  99729. BABYLON.Tools.SetCorsBehavior(this.url, img);
  99730. img.onload = function () {
  99731. _this.image = img;
  99732. onSuccess();
  99733. };
  99734. img.onerror = function (err) {
  99735. onError("Error loading image", err);
  99736. };
  99737. img.src = this.url;
  99738. };
  99739. return ImageAssetTask;
  99740. }(AbstractAssetTask));
  99741. BABYLON.ImageAssetTask = ImageAssetTask;
  99742. /**
  99743. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  99744. */
  99745. var TextureAssetTask = /** @class */ (function (_super) {
  99746. __extends(TextureAssetTask, _super);
  99747. /**
  99748. * Creates a new TextureAssetTask object
  99749. * @param name defines the name of the task
  99750. * @param url defines the location of the file to load
  99751. * @param noMipmap defines if mipmap should not be generated (default is false)
  99752. * @param invertY defines if texture must be inverted on Y axis (default is false)
  99753. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99754. */
  99755. function TextureAssetTask(
  99756. /**
  99757. * Defines the name of the task
  99758. */
  99759. name,
  99760. /**
  99761. * Defines the location of the file to load
  99762. */
  99763. url,
  99764. /**
  99765. * Defines if mipmap should not be generated (default is false)
  99766. */
  99767. noMipmap,
  99768. /**
  99769. * Defines if texture must be inverted on Y axis (default is false)
  99770. */
  99771. invertY,
  99772. /**
  99773. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99774. */
  99775. samplingMode) {
  99776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99777. var _this = _super.call(this, name) || this;
  99778. _this.name = name;
  99779. _this.url = url;
  99780. _this.noMipmap = noMipmap;
  99781. _this.invertY = invertY;
  99782. _this.samplingMode = samplingMode;
  99783. return _this;
  99784. }
  99785. /**
  99786. * Execute the current task
  99787. * @param scene defines the scene where you want your assets to be loaded
  99788. * @param onSuccess is a callback called when the task is successfully executed
  99789. * @param onError is a callback called if an error occurs
  99790. */
  99791. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99792. var onload = function () {
  99793. onSuccess();
  99794. };
  99795. var onerror = function (message, exception) {
  99796. onError(message, exception);
  99797. };
  99798. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  99799. };
  99800. return TextureAssetTask;
  99801. }(AbstractAssetTask));
  99802. BABYLON.TextureAssetTask = TextureAssetTask;
  99803. /**
  99804. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  99805. */
  99806. var CubeTextureAssetTask = /** @class */ (function (_super) {
  99807. __extends(CubeTextureAssetTask, _super);
  99808. /**
  99809. * Creates a new CubeTextureAssetTask
  99810. * @param name defines the name of the task
  99811. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99812. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99813. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99814. * @param files defines the explicit list of files (undefined by default)
  99815. */
  99816. function CubeTextureAssetTask(
  99817. /**
  99818. * Defines the name of the task
  99819. */
  99820. name,
  99821. /**
  99822. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99823. */
  99824. url,
  99825. /**
  99826. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99827. */
  99828. extensions,
  99829. /**
  99830. * Defines if mipmaps should not be generated (default is false)
  99831. */
  99832. noMipmap,
  99833. /**
  99834. * Defines the explicit list of files (undefined by default)
  99835. */
  99836. files) {
  99837. var _this = _super.call(this, name) || this;
  99838. _this.name = name;
  99839. _this.url = url;
  99840. _this.extensions = extensions;
  99841. _this.noMipmap = noMipmap;
  99842. _this.files = files;
  99843. return _this;
  99844. }
  99845. /**
  99846. * Execute the current task
  99847. * @param scene defines the scene where you want your assets to be loaded
  99848. * @param onSuccess is a callback called when the task is successfully executed
  99849. * @param onError is a callback called if an error occurs
  99850. */
  99851. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99852. var onload = function () {
  99853. onSuccess();
  99854. };
  99855. var onerror = function (message, exception) {
  99856. onError(message, exception);
  99857. };
  99858. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  99859. };
  99860. return CubeTextureAssetTask;
  99861. }(AbstractAssetTask));
  99862. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  99863. /**
  99864. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  99865. */
  99866. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  99867. __extends(HDRCubeTextureAssetTask, _super);
  99868. /**
  99869. * Creates a new HDRCubeTextureAssetTask object
  99870. * @param name defines the name of the task
  99871. * @param url defines the location of the file to load
  99872. * @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.
  99873. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99874. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99875. * @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)
  99876. * @param reserved Internal use only
  99877. */
  99878. function HDRCubeTextureAssetTask(
  99879. /**
  99880. * Defines the name of the task
  99881. */
  99882. name,
  99883. /**
  99884. * Defines the location of the file to load
  99885. */
  99886. url,
  99887. /**
  99888. * Defines the desired size (the more it increases the longer the generation will be)
  99889. */
  99890. size,
  99891. /**
  99892. * Defines if mipmaps should not be generated (default is false)
  99893. */
  99894. noMipmap,
  99895. /**
  99896. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99897. */
  99898. generateHarmonics,
  99899. /**
  99900. * 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)
  99901. */
  99902. gammaSpace,
  99903. /**
  99904. * Internal Use Only
  99905. */
  99906. reserved) {
  99907. if (noMipmap === void 0) { noMipmap = false; }
  99908. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99909. if (gammaSpace === void 0) { gammaSpace = false; }
  99910. if (reserved === void 0) { reserved = false; }
  99911. var _this = _super.call(this, name) || this;
  99912. _this.name = name;
  99913. _this.url = url;
  99914. _this.size = size;
  99915. _this.noMipmap = noMipmap;
  99916. _this.generateHarmonics = generateHarmonics;
  99917. _this.gammaSpace = gammaSpace;
  99918. _this.reserved = reserved;
  99919. return _this;
  99920. }
  99921. /**
  99922. * Execute the current task
  99923. * @param scene defines the scene where you want your assets to be loaded
  99924. * @param onSuccess is a callback called when the task is successfully executed
  99925. * @param onError is a callback called if an error occurs
  99926. */
  99927. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99928. var onload = function () {
  99929. onSuccess();
  99930. };
  99931. var onerror = function (message, exception) {
  99932. onError(message, exception);
  99933. };
  99934. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  99935. };
  99936. return HDRCubeTextureAssetTask;
  99937. }(AbstractAssetTask));
  99938. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  99939. /**
  99940. * This class can be used to easily import assets into a scene
  99941. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  99942. */
  99943. var AssetsManager = /** @class */ (function () {
  99944. /**
  99945. * Creates a new AssetsManager
  99946. * @param scene defines the scene to work on
  99947. */
  99948. function AssetsManager(scene) {
  99949. this._isLoading = false;
  99950. this._tasks = new Array();
  99951. this._waitingTasksCount = 0;
  99952. this._totalTasksCount = 0;
  99953. /**
  99954. * Observable called when all tasks are processed
  99955. */
  99956. this.onTaskSuccessObservable = new BABYLON.Observable();
  99957. /**
  99958. * Observable called when a task had an error
  99959. */
  99960. this.onTaskErrorObservable = new BABYLON.Observable();
  99961. /**
  99962. * Observable called when a task is successful
  99963. */
  99964. this.onTasksDoneObservable = new BABYLON.Observable();
  99965. /**
  99966. * Observable called when a task is done (whatever the result is)
  99967. */
  99968. this.onProgressObservable = new BABYLON.Observable();
  99969. /**
  99970. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  99971. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  99972. */
  99973. this.useDefaultLoadingScreen = true;
  99974. this._scene = scene;
  99975. }
  99976. /**
  99977. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  99978. * @param taskName defines the name of the new task
  99979. * @param meshesNames defines the name of meshes to load
  99980. * @param rootUrl defines the root url to use to locate files
  99981. * @param sceneFilename defines the filename of the scene file
  99982. * @returns a new {BABYLON.MeshAssetTask} object
  99983. */
  99984. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  99985. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  99986. this._tasks.push(task);
  99987. return task;
  99988. };
  99989. /**
  99990. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  99991. * @param taskName defines the name of the new task
  99992. * @param url defines the url of the file to load
  99993. * @returns a new {BABYLON.TextFileAssetTask} object
  99994. */
  99995. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  99996. var task = new TextFileAssetTask(taskName, url);
  99997. this._tasks.push(task);
  99998. return task;
  99999. };
  100000. /**
  100001. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  100002. * @param taskName defines the name of the new task
  100003. * @param url defines the url of the file to load
  100004. * @returns a new {BABYLON.BinaryFileAssetTask} object
  100005. */
  100006. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  100007. var task = new BinaryFileAssetTask(taskName, url);
  100008. this._tasks.push(task);
  100009. return task;
  100010. };
  100011. /**
  100012. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  100013. * @param taskName defines the name of the new task
  100014. * @param url defines the url of the file to load
  100015. * @returns a new {BABYLON.ImageAssetTask} object
  100016. */
  100017. AssetsManager.prototype.addImageTask = function (taskName, url) {
  100018. var task = new ImageAssetTask(taskName, url);
  100019. this._tasks.push(task);
  100020. return task;
  100021. };
  100022. /**
  100023. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  100024. * @param taskName defines the name of the new task
  100025. * @param url defines the url of the file to load
  100026. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100027. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  100028. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  100029. * @returns a new {BABYLON.TextureAssetTask} object
  100030. */
  100031. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  100032. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100033. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  100034. this._tasks.push(task);
  100035. return task;
  100036. };
  100037. /**
  100038. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  100039. * @param taskName defines the name of the new task
  100040. * @param url defines the url of the file to load
  100041. * @param extensions defines the extension to use to load the cube map (can be null)
  100042. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100043. * @param files defines the list of files to load (can be null)
  100044. * @returns a new {BABYLON.CubeTextureAssetTask} object
  100045. */
  100046. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  100047. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  100048. this._tasks.push(task);
  100049. return task;
  100050. };
  100051. /**
  100052. *
  100053. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  100054. * @param taskName defines the name of the new task
  100055. * @param url defines the url of the file to load
  100056. * @param size defines the size you want for the cubemap (can be null)
  100057. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100058. * @param generateHarmonics defines if you want to automatically generate (true by default)
  100059. * @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)
  100060. * @param reserved Internal use only
  100061. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  100062. */
  100063. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  100064. if (noMipmap === void 0) { noMipmap = false; }
  100065. if (generateHarmonics === void 0) { generateHarmonics = true; }
  100066. if (gammaSpace === void 0) { gammaSpace = false; }
  100067. if (reserved === void 0) { reserved = false; }
  100068. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  100069. this._tasks.push(task);
  100070. return task;
  100071. };
  100072. /**
  100073. * Remove a task from the assets manager.
  100074. * @param task the task to remove
  100075. */
  100076. AssetsManager.prototype.removeTask = function (task) {
  100077. var index = this._tasks.indexOf(task);
  100078. if (index > -1) {
  100079. this._tasks.splice(index, 1);
  100080. }
  100081. };
  100082. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  100083. this._waitingTasksCount--;
  100084. try {
  100085. if (this.onProgress) {
  100086. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  100087. }
  100088. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  100089. }
  100090. catch (e) {
  100091. BABYLON.Tools.Error("Error running progress callbacks.");
  100092. console.log(e);
  100093. }
  100094. if (this._waitingTasksCount === 0) {
  100095. try {
  100096. if (this.onFinish) {
  100097. this.onFinish(this._tasks);
  100098. }
  100099. // Let's remove successfull tasks
  100100. var currentTasks = this._tasks.slice();
  100101. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  100102. var task = currentTasks_1[_i];
  100103. if (task.taskState === AssetTaskState.DONE) {
  100104. var index = this._tasks.indexOf(task);
  100105. if (index > -1) {
  100106. this._tasks.splice(index, 1);
  100107. }
  100108. }
  100109. }
  100110. this.onTasksDoneObservable.notifyObservers(this._tasks);
  100111. }
  100112. catch (e) {
  100113. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  100114. console.log(e);
  100115. }
  100116. this._isLoading = false;
  100117. this._scene.getEngine().hideLoadingUI();
  100118. }
  100119. };
  100120. AssetsManager.prototype._runTask = function (task) {
  100121. var _this = this;
  100122. var done = function () {
  100123. try {
  100124. if (_this.onTaskSuccess) {
  100125. _this.onTaskSuccess(task);
  100126. }
  100127. _this.onTaskSuccessObservable.notifyObservers(task);
  100128. _this._decreaseWaitingTasksCount(task);
  100129. }
  100130. catch (e) {
  100131. error("Error executing task success callbacks", e);
  100132. }
  100133. };
  100134. var error = function (message, exception) {
  100135. task._setErrorObject(message, exception);
  100136. if (_this.onTaskError) {
  100137. _this.onTaskError(task);
  100138. }
  100139. _this.onTaskErrorObservable.notifyObservers(task);
  100140. _this._decreaseWaitingTasksCount(task);
  100141. };
  100142. task.run(this._scene, done, error);
  100143. };
  100144. /**
  100145. * Reset the {BABYLON.AssetsManager} and remove all tasks
  100146. * @return the current instance of the {BABYLON.AssetsManager}
  100147. */
  100148. AssetsManager.prototype.reset = function () {
  100149. this._isLoading = false;
  100150. this._tasks = new Array();
  100151. return this;
  100152. };
  100153. /**
  100154. * Start the loading process
  100155. * @return the current instance of the {BABYLON.AssetsManager}
  100156. */
  100157. AssetsManager.prototype.load = function () {
  100158. if (this._isLoading) {
  100159. return this;
  100160. }
  100161. this._isLoading = true;
  100162. this._waitingTasksCount = this._tasks.length;
  100163. this._totalTasksCount = this._tasks.length;
  100164. if (this._waitingTasksCount === 0) {
  100165. this._isLoading = false;
  100166. if (this.onFinish) {
  100167. this.onFinish(this._tasks);
  100168. }
  100169. this.onTasksDoneObservable.notifyObservers(this._tasks);
  100170. return this;
  100171. }
  100172. if (this.useDefaultLoadingScreen) {
  100173. this._scene.getEngine().displayLoadingUI();
  100174. }
  100175. for (var index = 0; index < this._tasks.length; index++) {
  100176. var task = this._tasks[index];
  100177. if (task.taskState === AssetTaskState.INIT) {
  100178. this._runTask(task);
  100179. }
  100180. }
  100181. return this;
  100182. };
  100183. return AssetsManager;
  100184. }());
  100185. BABYLON.AssetsManager = AssetsManager;
  100186. })(BABYLON || (BABYLON = {}));
  100187. //# sourceMappingURL=babylon.assetsManager.js.map
  100188. var BABYLON;
  100189. (function (BABYLON) {
  100190. var serializedGeometries = [];
  100191. var serializeGeometry = function (geometry, serializationGeometries) {
  100192. if (serializedGeometries[geometry.id]) {
  100193. return;
  100194. }
  100195. if (geometry.doNotSerialize) {
  100196. return;
  100197. }
  100198. if (geometry instanceof BABYLON.BoxGeometry) {
  100199. serializationGeometries.boxes.push(geometry.serialize());
  100200. }
  100201. else if (geometry instanceof BABYLON.SphereGeometry) {
  100202. serializationGeometries.spheres.push(geometry.serialize());
  100203. }
  100204. else if (geometry instanceof BABYLON.CylinderGeometry) {
  100205. serializationGeometries.cylinders.push(geometry.serialize());
  100206. }
  100207. else if (geometry instanceof BABYLON.TorusGeometry) {
  100208. serializationGeometries.toruses.push(geometry.serialize());
  100209. }
  100210. else if (geometry instanceof BABYLON.GroundGeometry) {
  100211. serializationGeometries.grounds.push(geometry.serialize());
  100212. }
  100213. else if (geometry instanceof BABYLON.Plane) {
  100214. serializationGeometries.planes.push(geometry.serialize());
  100215. }
  100216. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  100217. serializationGeometries.torusKnots.push(geometry.serialize());
  100218. }
  100219. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  100220. throw new Error("Unknown primitive type");
  100221. }
  100222. else {
  100223. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  100224. }
  100225. serializedGeometries[geometry.id] = true;
  100226. };
  100227. var serializeMesh = function (mesh, serializationScene) {
  100228. var serializationObject = {};
  100229. // Geometry
  100230. var geometry = mesh._geometry;
  100231. if (geometry) {
  100232. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  100233. // 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
  100234. serializeGeometry(geometry, serializationScene.geometries);
  100235. }
  100236. }
  100237. // Custom
  100238. if (mesh.serialize) {
  100239. mesh.serialize(serializationObject);
  100240. }
  100241. return serializationObject;
  100242. };
  100243. var finalizeSingleMesh = function (mesh, serializationObject) {
  100244. //only works if the mesh is already loaded
  100245. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  100246. //serialize material
  100247. if (mesh.material) {
  100248. if (mesh.material instanceof BABYLON.MultiMaterial) {
  100249. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  100250. serializationObject.materials = serializationObject.materials || [];
  100251. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  100252. serializationObject.multiMaterials.push(mesh.material.serialize());
  100253. var _loop_1 = function (submaterial) {
  100254. if (submaterial) {
  100255. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  100256. serializationObject.materials.push(submaterial.serialize());
  100257. }
  100258. }
  100259. };
  100260. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  100261. var submaterial = _a[_i];
  100262. _loop_1(submaterial);
  100263. }
  100264. }
  100265. }
  100266. else {
  100267. serializationObject.materials = serializationObject.materials || [];
  100268. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  100269. serializationObject.materials.push(mesh.material.serialize());
  100270. }
  100271. }
  100272. }
  100273. //serialize geometry
  100274. var geometry = mesh._geometry;
  100275. if (geometry) {
  100276. if (!serializationObject.geometries) {
  100277. serializationObject.geometries = {};
  100278. serializationObject.geometries.boxes = [];
  100279. serializationObject.geometries.spheres = [];
  100280. serializationObject.geometries.cylinders = [];
  100281. serializationObject.geometries.toruses = [];
  100282. serializationObject.geometries.grounds = [];
  100283. serializationObject.geometries.planes = [];
  100284. serializationObject.geometries.torusKnots = [];
  100285. serializationObject.geometries.vertexData = [];
  100286. }
  100287. serializeGeometry(geometry, serializationObject.geometries);
  100288. }
  100289. // Skeletons
  100290. if (mesh.skeleton) {
  100291. serializationObject.skeletons = serializationObject.skeletons || [];
  100292. serializationObject.skeletons.push(mesh.skeleton.serialize());
  100293. }
  100294. //serialize the actual mesh
  100295. serializationObject.meshes = serializationObject.meshes || [];
  100296. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  100297. }
  100298. };
  100299. var SceneSerializer = /** @class */ (function () {
  100300. function SceneSerializer() {
  100301. }
  100302. SceneSerializer.ClearCache = function () {
  100303. serializedGeometries = [];
  100304. };
  100305. SceneSerializer.Serialize = function (scene) {
  100306. var serializationObject = {};
  100307. SceneSerializer.ClearCache();
  100308. // Scene
  100309. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  100310. serializationObject.autoClear = scene.autoClear;
  100311. serializationObject.clearColor = scene.clearColor.asArray();
  100312. serializationObject.ambientColor = scene.ambientColor.asArray();
  100313. serializationObject.gravity = scene.gravity.asArray();
  100314. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  100315. serializationObject.workerCollisions = scene.workerCollisions;
  100316. // Fog
  100317. if (scene.fogMode && scene.fogMode !== 0) {
  100318. serializationObject.fogMode = scene.fogMode;
  100319. serializationObject.fogColor = scene.fogColor.asArray();
  100320. serializationObject.fogStart = scene.fogStart;
  100321. serializationObject.fogEnd = scene.fogEnd;
  100322. serializationObject.fogDensity = scene.fogDensity;
  100323. }
  100324. //Physics
  100325. if (scene.isPhysicsEnabled()) {
  100326. var physicEngine = scene.getPhysicsEngine();
  100327. if (physicEngine) {
  100328. serializationObject.physicsEnabled = true;
  100329. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  100330. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  100331. }
  100332. }
  100333. // Metadata
  100334. if (scene.metadata) {
  100335. serializationObject.metadata = scene.metadata;
  100336. }
  100337. // Morph targets
  100338. serializationObject.morphTargetManagers = [];
  100339. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  100340. var abstractMesh = _a[_i];
  100341. var manager = abstractMesh.morphTargetManager;
  100342. if (manager) {
  100343. serializationObject.morphTargetManagers.push(manager.serialize());
  100344. }
  100345. }
  100346. // Lights
  100347. serializationObject.lights = [];
  100348. var index;
  100349. var light;
  100350. for (index = 0; index < scene.lights.length; index++) {
  100351. light = scene.lights[index];
  100352. if (!light.doNotSerialize) {
  100353. serializationObject.lights.push(light.serialize());
  100354. }
  100355. }
  100356. // Cameras
  100357. serializationObject.cameras = [];
  100358. for (index = 0; index < scene.cameras.length; index++) {
  100359. var camera = scene.cameras[index];
  100360. if (!camera.doNotSerialize) {
  100361. serializationObject.cameras.push(camera.serialize());
  100362. }
  100363. }
  100364. if (scene.activeCamera) {
  100365. serializationObject.activeCameraID = scene.activeCamera.id;
  100366. }
  100367. // Animations
  100368. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  100369. // Materials
  100370. serializationObject.materials = [];
  100371. serializationObject.multiMaterials = [];
  100372. var material;
  100373. for (index = 0; index < scene.materials.length; index++) {
  100374. material = scene.materials[index];
  100375. if (!material.doNotSerialize) {
  100376. serializationObject.materials.push(material.serialize());
  100377. }
  100378. }
  100379. // MultiMaterials
  100380. serializationObject.multiMaterials = [];
  100381. for (index = 0; index < scene.multiMaterials.length; index++) {
  100382. var multiMaterial = scene.multiMaterials[index];
  100383. serializationObject.multiMaterials.push(multiMaterial.serialize());
  100384. }
  100385. // Environment texture
  100386. if (scene.environmentTexture) {
  100387. serializationObject.environmentTexture = scene.environmentTexture.name;
  100388. }
  100389. // Skeletons
  100390. serializationObject.skeletons = [];
  100391. for (index = 0; index < scene.skeletons.length; index++) {
  100392. var skeleton = scene.skeletons[index];
  100393. if (!skeleton.doNotSerialize) {
  100394. serializationObject.skeletons.push(skeleton.serialize());
  100395. }
  100396. }
  100397. // Transform nodes
  100398. serializationObject.transformNodes = [];
  100399. for (index = 0; index < scene.transformNodes.length; index++) {
  100400. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  100401. }
  100402. // Geometries
  100403. serializationObject.geometries = {};
  100404. serializationObject.geometries.boxes = [];
  100405. serializationObject.geometries.spheres = [];
  100406. serializationObject.geometries.cylinders = [];
  100407. serializationObject.geometries.toruses = [];
  100408. serializationObject.geometries.grounds = [];
  100409. serializationObject.geometries.planes = [];
  100410. serializationObject.geometries.torusKnots = [];
  100411. serializationObject.geometries.vertexData = [];
  100412. serializedGeometries = [];
  100413. var geometries = scene.getGeometries();
  100414. for (index = 0; index < geometries.length; index++) {
  100415. var geometry = geometries[index];
  100416. if (geometry.isReady()) {
  100417. serializeGeometry(geometry, serializationObject.geometries);
  100418. }
  100419. }
  100420. // Meshes
  100421. serializationObject.meshes = [];
  100422. for (index = 0; index < scene.meshes.length; index++) {
  100423. var abstractMesh = scene.meshes[index];
  100424. if (abstractMesh instanceof BABYLON.Mesh) {
  100425. var mesh = abstractMesh;
  100426. if (!mesh.doNotSerialize) {
  100427. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  100428. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  100429. }
  100430. }
  100431. }
  100432. }
  100433. // Particles Systems
  100434. serializationObject.particleSystems = [];
  100435. for (index = 0; index < scene.particleSystems.length; index++) {
  100436. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  100437. }
  100438. // Shadows
  100439. serializationObject.shadowGenerators = [];
  100440. for (index = 0; index < scene.lights.length; index++) {
  100441. light = scene.lights[index];
  100442. var shadowGenerator = light.getShadowGenerator();
  100443. if (shadowGenerator) {
  100444. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  100445. }
  100446. }
  100447. // Action Manager
  100448. if (scene.actionManager) {
  100449. serializationObject.actions = scene.actionManager.serialize("scene");
  100450. }
  100451. // Audio
  100452. serializationObject.sounds = [];
  100453. for (index = 0; index < scene.soundTracks.length; index++) {
  100454. var soundtrack = scene.soundTracks[index];
  100455. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  100456. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  100457. }
  100458. }
  100459. // Components
  100460. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  100461. var component = _c[_b];
  100462. component.serialize(serializationObject);
  100463. }
  100464. return serializationObject;
  100465. };
  100466. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  100467. if (withParents === void 0) { withParents = false; }
  100468. if (withChildren === void 0) { withChildren = false; }
  100469. var serializationObject = {};
  100470. SceneSerializer.ClearCache();
  100471. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  100472. if (withParents || withChildren) {
  100473. //deliberate for loop! not for each, appended should be processed as well.
  100474. for (var i = 0; i < toSerialize.length; ++i) {
  100475. if (withChildren) {
  100476. toSerialize[i].getDescendants().forEach(function (node) {
  100477. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  100478. toSerialize.push(node);
  100479. }
  100480. });
  100481. }
  100482. //make sure the array doesn't contain the object already
  100483. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  100484. toSerialize.push(toSerialize[i].parent);
  100485. }
  100486. }
  100487. }
  100488. toSerialize.forEach(function (mesh) {
  100489. finalizeSingleMesh(mesh, serializationObject);
  100490. });
  100491. return serializationObject;
  100492. };
  100493. return SceneSerializer;
  100494. }());
  100495. BABYLON.SceneSerializer = SceneSerializer;
  100496. })(BABYLON || (BABYLON = {}));
  100497. //# sourceMappingURL=babylon.sceneSerializer.js.map
  100498. var BABYLON;
  100499. (function (BABYLON) {
  100500. var ReflectionProbe = /** @class */ (function () {
  100501. function ReflectionProbe(name, size, scene, generateMipMaps) {
  100502. if (generateMipMaps === void 0) { generateMipMaps = true; }
  100503. var _this = this;
  100504. this.name = name;
  100505. this._viewMatrix = BABYLON.Matrix.Identity();
  100506. this._target = BABYLON.Vector3.Zero();
  100507. this._add = BABYLON.Vector3.Zero();
  100508. this._invertYAxis = false;
  100509. this.position = BABYLON.Vector3.Zero();
  100510. this._scene = scene;
  100511. this._scene.reflectionProbes.push(this);
  100512. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  100513. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  100514. switch (faceIndex) {
  100515. case 0:
  100516. _this._add.copyFromFloats(1, 0, 0);
  100517. break;
  100518. case 1:
  100519. _this._add.copyFromFloats(-1, 0, 0);
  100520. break;
  100521. case 2:
  100522. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  100523. break;
  100524. case 3:
  100525. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  100526. break;
  100527. case 4:
  100528. _this._add.copyFromFloats(0, 0, 1);
  100529. break;
  100530. case 5:
  100531. _this._add.copyFromFloats(0, 0, -1);
  100532. break;
  100533. }
  100534. if (_this._attachedMesh) {
  100535. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  100536. }
  100537. _this.position.addToRef(_this._add, _this._target);
  100538. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  100539. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  100540. scene._forcedViewPosition = _this.position;
  100541. });
  100542. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  100543. scene._forcedViewPosition = null;
  100544. scene.updateTransformMatrix(true);
  100545. });
  100546. if (scene.activeCamera) {
  100547. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  100548. }
  100549. }
  100550. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  100551. get: function () {
  100552. return this._renderTargetTexture.samples;
  100553. },
  100554. set: function (value) {
  100555. this._renderTargetTexture.samples = value;
  100556. },
  100557. enumerable: true,
  100558. configurable: true
  100559. });
  100560. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  100561. get: function () {
  100562. return this._renderTargetTexture.refreshRate;
  100563. },
  100564. set: function (value) {
  100565. this._renderTargetTexture.refreshRate = value;
  100566. },
  100567. enumerable: true,
  100568. configurable: true
  100569. });
  100570. ReflectionProbe.prototype.getScene = function () {
  100571. return this._scene;
  100572. };
  100573. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  100574. get: function () {
  100575. return this._renderTargetTexture;
  100576. },
  100577. enumerable: true,
  100578. configurable: true
  100579. });
  100580. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  100581. get: function () {
  100582. return this._renderTargetTexture.renderList;
  100583. },
  100584. enumerable: true,
  100585. configurable: true
  100586. });
  100587. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  100588. this._attachedMesh = mesh;
  100589. };
  100590. /**
  100591. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  100592. *
  100593. * @param renderingGroupId The rendering group id corresponding to its index
  100594. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  100595. */
  100596. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  100597. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  100598. };
  100599. ReflectionProbe.prototype.dispose = function () {
  100600. var index = this._scene.reflectionProbes.indexOf(this);
  100601. if (index !== -1) {
  100602. // Remove from the scene if found
  100603. this._scene.reflectionProbes.splice(index, 1);
  100604. }
  100605. if (this._renderTargetTexture) {
  100606. this._renderTargetTexture.dispose();
  100607. this._renderTargetTexture = null;
  100608. }
  100609. };
  100610. return ReflectionProbe;
  100611. }());
  100612. BABYLON.ReflectionProbe = ReflectionProbe;
  100613. })(BABYLON || (BABYLON = {}));
  100614. //# sourceMappingURL=babylon.reflectionProbe.js.map
  100615. var BABYLON;
  100616. (function (BABYLON) {
  100617. /**
  100618. * Defines the layer scene component responsible to manage any layers
  100619. * in a given scene.
  100620. */
  100621. var LayerSceneComponent = /** @class */ (function () {
  100622. /**
  100623. * Creates a new instance of the component for the given scene
  100624. * @param scene Defines the scene to register the component in
  100625. */
  100626. function LayerSceneComponent(scene) {
  100627. /**
  100628. * The component name helpfull to identify the component in the list of scene components.
  100629. */
  100630. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  100631. this.scene = scene;
  100632. this._engine = scene.getEngine();
  100633. scene.layers = new Array();
  100634. }
  100635. /**
  100636. * Registers the component in a given scene
  100637. */
  100638. LayerSceneComponent.prototype.register = function () {
  100639. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  100640. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  100641. };
  100642. /**
  100643. * Rebuilds the elements related to this component in case of
  100644. * context lost for instance.
  100645. */
  100646. LayerSceneComponent.prototype.rebuild = function () {
  100647. var layers = this.scene.layers;
  100648. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100649. var layer = layers_1[_i];
  100650. layer._rebuild();
  100651. }
  100652. };
  100653. /**
  100654. * Disposes the component and the associated ressources.
  100655. */
  100656. LayerSceneComponent.prototype.dispose = function () {
  100657. var layers = this.scene.layers;
  100658. while (layers.length) {
  100659. layers[0].dispose();
  100660. }
  100661. };
  100662. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  100663. var layers = this.scene.layers;
  100664. if (layers.length) {
  100665. this._engine.setDepthBuffer(false);
  100666. var cameraLayerMask = camera.layerMask;
  100667. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100668. var layer = layers_2[_i];
  100669. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  100670. layer.render();
  100671. }
  100672. }
  100673. this._engine.setDepthBuffer(true);
  100674. }
  100675. };
  100676. LayerSceneComponent.prototype._drawBackground = function (camera) {
  100677. this._draw(camera, true);
  100678. };
  100679. LayerSceneComponent.prototype._drawForeground = function (camera) {
  100680. this._draw(camera, false);
  100681. };
  100682. return LayerSceneComponent;
  100683. }());
  100684. BABYLON.LayerSceneComponent = LayerSceneComponent;
  100685. })(BABYLON || (BABYLON = {}));
  100686. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  100687. var BABYLON;
  100688. (function (BABYLON) {
  100689. var Layer = /** @class */ (function () {
  100690. function Layer(name, imgUrl, scene, isBackground, color) {
  100691. this.name = name;
  100692. this.scale = new BABYLON.Vector2(1, 1);
  100693. this.offset = new BABYLON.Vector2(0, 0);
  100694. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  100695. this.layerMask = 0x0FFFFFFF;
  100696. this._vertexBuffers = {};
  100697. // Events
  100698. /**
  100699. * An event triggered when the layer is disposed.
  100700. */
  100701. this.onDisposeObservable = new BABYLON.Observable();
  100702. /**
  100703. * An event triggered before rendering the scene
  100704. */
  100705. this.onBeforeRenderObservable = new BABYLON.Observable();
  100706. /**
  100707. * An event triggered after rendering the scene
  100708. */
  100709. this.onAfterRenderObservable = new BABYLON.Observable();
  100710. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  100711. this.isBackground = isBackground === undefined ? true : isBackground;
  100712. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  100713. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  100714. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  100715. if (!layerComponent) {
  100716. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  100717. this._scene._addComponent(layerComponent);
  100718. }
  100719. this._scene.layers.push(this);
  100720. var engine = this._scene.getEngine();
  100721. // VBO
  100722. var vertices = [];
  100723. vertices.push(1, 1);
  100724. vertices.push(-1, 1);
  100725. vertices.push(-1, -1);
  100726. vertices.push(1, -1);
  100727. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100728. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100729. this._createIndexBuffer();
  100730. // Effects
  100731. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  100732. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  100733. }
  100734. Object.defineProperty(Layer.prototype, "onDispose", {
  100735. set: function (callback) {
  100736. if (this._onDisposeObserver) {
  100737. this.onDisposeObservable.remove(this._onDisposeObserver);
  100738. }
  100739. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100740. },
  100741. enumerable: true,
  100742. configurable: true
  100743. });
  100744. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  100745. set: function (callback) {
  100746. if (this._onBeforeRenderObserver) {
  100747. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100748. }
  100749. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  100750. },
  100751. enumerable: true,
  100752. configurable: true
  100753. });
  100754. Object.defineProperty(Layer.prototype, "onAfterRender", {
  100755. set: function (callback) {
  100756. if (this._onAfterRenderObserver) {
  100757. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100758. }
  100759. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  100760. },
  100761. enumerable: true,
  100762. configurable: true
  100763. });
  100764. Layer.prototype._createIndexBuffer = function () {
  100765. var engine = this._scene.getEngine();
  100766. // Indices
  100767. var indices = [];
  100768. indices.push(0);
  100769. indices.push(1);
  100770. indices.push(2);
  100771. indices.push(0);
  100772. indices.push(2);
  100773. indices.push(3);
  100774. this._indexBuffer = engine.createIndexBuffer(indices);
  100775. };
  100776. Layer.prototype._rebuild = function () {
  100777. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100778. if (vb) {
  100779. vb._rebuild();
  100780. }
  100781. this._createIndexBuffer();
  100782. };
  100783. Layer.prototype.render = function () {
  100784. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  100785. // Check
  100786. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  100787. return;
  100788. var engine = this._scene.getEngine();
  100789. this.onBeforeRenderObservable.notifyObservers(this);
  100790. // Render
  100791. engine.enableEffect(currentEffect);
  100792. engine.setState(false);
  100793. // Texture
  100794. currentEffect.setTexture("textureSampler", this.texture);
  100795. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  100796. // Color
  100797. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  100798. // Scale / offset
  100799. currentEffect.setVector2("offset", this.offset);
  100800. currentEffect.setVector2("scale", this.scale);
  100801. // VBOs
  100802. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100803. // Draw order
  100804. if (!this.alphaTest) {
  100805. engine.setAlphaMode(this.alphaBlendingMode);
  100806. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100807. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100808. }
  100809. else {
  100810. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100811. }
  100812. this.onAfterRenderObservable.notifyObservers(this);
  100813. };
  100814. Layer.prototype.dispose = function () {
  100815. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100816. if (vertexBuffer) {
  100817. vertexBuffer.dispose();
  100818. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100819. }
  100820. if (this._indexBuffer) {
  100821. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100822. this._indexBuffer = null;
  100823. }
  100824. if (this.texture) {
  100825. this.texture.dispose();
  100826. this.texture = null;
  100827. }
  100828. // Remove from scene
  100829. var index = this._scene.layers.indexOf(this);
  100830. this._scene.layers.splice(index, 1);
  100831. // Callback
  100832. this.onDisposeObservable.notifyObservers(this);
  100833. this.onDisposeObservable.clear();
  100834. this.onAfterRenderObservable.clear();
  100835. this.onBeforeRenderObservable.clear();
  100836. };
  100837. return Layer;
  100838. }());
  100839. BABYLON.Layer = Layer;
  100840. })(BABYLON || (BABYLON = {}));
  100841. //# sourceMappingURL=babylon.layer.js.map
  100842. var BABYLON;
  100843. (function (BABYLON) {
  100844. var TextureTools = /** @class */ (function () {
  100845. function TextureTools() {
  100846. }
  100847. /**
  100848. * Uses the GPU to create a copy texture rescaled at a given size
  100849. * @param texture Texture to copy from
  100850. * @param width Desired width
  100851. * @param height Desired height
  100852. * @return Generated texture
  100853. */
  100854. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  100855. if (useBilinearMode === void 0) { useBilinearMode = true; }
  100856. var scene = texture.getScene();
  100857. var engine = scene.getEngine();
  100858. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  100859. rtt.wrapU = texture.wrapU;
  100860. rtt.wrapV = texture.wrapV;
  100861. rtt.uOffset = texture.uOffset;
  100862. rtt.vOffset = texture.vOffset;
  100863. rtt.uScale = texture.uScale;
  100864. rtt.vScale = texture.vScale;
  100865. rtt.uAng = texture.uAng;
  100866. rtt.vAng = texture.vAng;
  100867. rtt.wAng = texture.wAng;
  100868. rtt.coordinatesIndex = texture.coordinatesIndex;
  100869. rtt.level = texture.level;
  100870. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  100871. rtt._texture.isReady = false;
  100872. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100873. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100874. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100875. passPostProcess.getEffect().executeWhenCompiled(function () {
  100876. passPostProcess.onApply = function (effect) {
  100877. effect.setTexture("textureSampler", texture);
  100878. };
  100879. var internalTexture = rtt.getInternalTexture();
  100880. if (internalTexture) {
  100881. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  100882. engine.unBindFramebuffer(internalTexture);
  100883. rtt.disposeFramebufferObjects();
  100884. passPostProcess.dispose();
  100885. internalTexture.isReady = true;
  100886. }
  100887. });
  100888. return rtt;
  100889. };
  100890. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  100891. if (!scene._environmentBRDFTexture) {
  100892. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100893. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100894. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100895. scene._environmentBRDFTexture = texture;
  100896. }
  100897. return scene._environmentBRDFTexture;
  100898. };
  100899. 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=";
  100900. return TextureTools;
  100901. }());
  100902. BABYLON.TextureTools = TextureTools;
  100903. })(BABYLON || (BABYLON = {}));
  100904. //# sourceMappingURL=babylon.textureTools.js.map
  100905. var BABYLON;
  100906. (function (BABYLON) {
  100907. var FramingBehavior = /** @class */ (function () {
  100908. function FramingBehavior() {
  100909. this._mode = FramingBehavior.FitFrustumSidesMode;
  100910. this._radiusScale = 1.0;
  100911. this._positionScale = 0.5;
  100912. this._defaultElevation = 0.3;
  100913. this._elevationReturnTime = 1500;
  100914. this._elevationReturnWaitTime = 1000;
  100915. this._zoomStopsAnimation = false;
  100916. this._framingTime = 1500;
  100917. this._isPointerDown = false;
  100918. this._lastInteractionTime = -Infinity;
  100919. // Framing control
  100920. this._animatables = new Array();
  100921. this._betaIsAnimating = false;
  100922. }
  100923. Object.defineProperty(FramingBehavior.prototype, "name", {
  100924. get: function () {
  100925. return "Framing";
  100926. },
  100927. enumerable: true,
  100928. configurable: true
  100929. });
  100930. Object.defineProperty(FramingBehavior.prototype, "mode", {
  100931. /**
  100932. * Gets current mode used by the behavior.
  100933. */
  100934. get: function () {
  100935. return this._mode;
  100936. },
  100937. /**
  100938. * Sets the current mode used by the behavior
  100939. */
  100940. set: function (mode) {
  100941. this._mode = mode;
  100942. },
  100943. enumerable: true,
  100944. configurable: true
  100945. });
  100946. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  100947. /**
  100948. * Gets the scale applied to the radius
  100949. */
  100950. get: function () {
  100951. return this._radiusScale;
  100952. },
  100953. /**
  100954. * Sets the scale applied to the radius (1 by default)
  100955. */
  100956. set: function (radius) {
  100957. this._radiusScale = radius;
  100958. },
  100959. enumerable: true,
  100960. configurable: true
  100961. });
  100962. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  100963. /**
  100964. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100965. */
  100966. get: function () {
  100967. return this._positionScale;
  100968. },
  100969. /**
  100970. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100971. */
  100972. set: function (scale) {
  100973. this._positionScale = scale;
  100974. },
  100975. enumerable: true,
  100976. configurable: true
  100977. });
  100978. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  100979. /**
  100980. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100981. * behaviour is triggered, in radians.
  100982. */
  100983. get: function () {
  100984. return this._defaultElevation;
  100985. },
  100986. /**
  100987. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100988. * behaviour is triggered, in radians.
  100989. */
  100990. set: function (elevation) {
  100991. this._defaultElevation = elevation;
  100992. },
  100993. enumerable: true,
  100994. configurable: true
  100995. });
  100996. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  100997. /**
  100998. * Gets the time (in milliseconds) taken to return to the default beta position.
  100999. * Negative value indicates camera should not return to default.
  101000. */
  101001. get: function () {
  101002. return this._elevationReturnTime;
  101003. },
  101004. /**
  101005. * Sets the time (in milliseconds) taken to return to the default beta position.
  101006. * Negative value indicates camera should not return to default.
  101007. */
  101008. set: function (speed) {
  101009. this._elevationReturnTime = speed;
  101010. },
  101011. enumerable: true,
  101012. configurable: true
  101013. });
  101014. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  101015. /**
  101016. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  101017. */
  101018. get: function () {
  101019. return this._elevationReturnWaitTime;
  101020. },
  101021. /**
  101022. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  101023. */
  101024. set: function (time) {
  101025. this._elevationReturnWaitTime = time;
  101026. },
  101027. enumerable: true,
  101028. configurable: true
  101029. });
  101030. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  101031. /**
  101032. * Gets the flag that indicates if user zooming should stop animation.
  101033. */
  101034. get: function () {
  101035. return this._zoomStopsAnimation;
  101036. },
  101037. /**
  101038. * Sets the flag that indicates if user zooming should stop animation.
  101039. */
  101040. set: function (flag) {
  101041. this._zoomStopsAnimation = flag;
  101042. },
  101043. enumerable: true,
  101044. configurable: true
  101045. });
  101046. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  101047. /**
  101048. * Gets the transition time when framing the mesh, in milliseconds
  101049. */
  101050. get: function () {
  101051. return this._framingTime;
  101052. },
  101053. /**
  101054. * Sets the transition time when framing the mesh, in milliseconds
  101055. */
  101056. set: function (time) {
  101057. this._framingTime = time;
  101058. },
  101059. enumerable: true,
  101060. configurable: true
  101061. });
  101062. FramingBehavior.prototype.init = function () {
  101063. // Do notihng
  101064. };
  101065. FramingBehavior.prototype.attach = function (camera) {
  101066. var _this = this;
  101067. this._attachedCamera = camera;
  101068. var scene = this._attachedCamera.getScene();
  101069. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  101070. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101071. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101072. _this._isPointerDown = true;
  101073. return;
  101074. }
  101075. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101076. _this._isPointerDown = false;
  101077. }
  101078. });
  101079. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  101080. if (mesh) {
  101081. _this.zoomOnMesh(mesh);
  101082. }
  101083. });
  101084. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101085. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101086. _this._applyUserInteraction();
  101087. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  101088. // back to the default position after a given timeout
  101089. _this._maintainCameraAboveGround();
  101090. });
  101091. };
  101092. FramingBehavior.prototype.detach = function () {
  101093. if (!this._attachedCamera) {
  101094. return;
  101095. }
  101096. var scene = this._attachedCamera.getScene();
  101097. if (this._onPrePointerObservableObserver) {
  101098. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101099. }
  101100. if (this._onAfterCheckInputsObserver) {
  101101. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101102. }
  101103. if (this._onMeshTargetChangedObserver) {
  101104. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101105. }
  101106. this._attachedCamera = null;
  101107. };
  101108. /**
  101109. * Targets the given mesh and updates zoom level accordingly.
  101110. * @param mesh The mesh to target.
  101111. * @param radius Optional. If a cached radius position already exists, overrides default.
  101112. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101113. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101114. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101115. */
  101116. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  101117. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101118. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101119. mesh.computeWorldMatrix(true);
  101120. var boundingBox = mesh.getBoundingInfo().boundingBox;
  101121. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  101122. };
  101123. /**
  101124. * Targets the given mesh with its children and updates zoom level accordingly.
  101125. * @param mesh The mesh to target.
  101126. * @param radius Optional. If a cached radius position already exists, overrides default.
  101127. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101128. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101129. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101130. */
  101131. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  101132. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101133. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101134. mesh.computeWorldMatrix(true);
  101135. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  101136. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  101137. };
  101138. /**
  101139. * Targets the given meshes with their children and updates zoom level accordingly.
  101140. * @param meshes The mesh to target.
  101141. * @param radius Optional. If a cached radius position already exists, overrides default.
  101142. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101143. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101144. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101145. */
  101146. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  101147. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101148. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101149. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  101150. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  101151. for (var i = 0; i < meshes.length; i++) {
  101152. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  101153. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  101154. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  101155. }
  101156. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  101157. };
  101158. /**
  101159. * Targets the given mesh and updates zoom level accordingly.
  101160. * @param mesh The mesh to target.
  101161. * @param radius Optional. If a cached radius position already exists, overrides default.
  101162. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101163. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101164. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101165. */
  101166. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  101167. var _this = this;
  101168. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101169. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101170. var zoomTarget;
  101171. if (!this._attachedCamera) {
  101172. return;
  101173. }
  101174. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  101175. var bottom = minimumWorld.y;
  101176. var top = maximumWorld.y;
  101177. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  101178. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  101179. if (focusOnOriginXZ) {
  101180. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  101181. }
  101182. else {
  101183. var centerWorld = minimumWorld.add(radiusWorld);
  101184. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  101185. }
  101186. if (!this._vectorTransition) {
  101187. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  101188. }
  101189. this._betaIsAnimating = true;
  101190. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  101191. if (animatable) {
  101192. this._animatables.push(animatable);
  101193. }
  101194. // sets the radius and lower radius bounds
  101195. // Small delta ensures camera is not always at lower zoom limit.
  101196. var radius = 0;
  101197. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  101198. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  101199. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  101200. radius = position;
  101201. }
  101202. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  101203. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  101204. if (this._attachedCamera.lowerRadiusLimit === null) {
  101205. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  101206. }
  101207. }
  101208. // Set sensibilities
  101209. var extend = maximumWorld.subtract(minimumWorld).length();
  101210. this._attachedCamera.panningSensibility = 5000 / extend;
  101211. this._attachedCamera.wheelPrecision = 100 / radius;
  101212. // transition to new radius
  101213. if (!this._radiusTransition) {
  101214. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  101215. }
  101216. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  101217. _this.stopAllAnimations();
  101218. if (onAnimationEnd) {
  101219. onAnimationEnd();
  101220. }
  101221. if (_this._attachedCamera) {
  101222. _this._attachedCamera.storeState();
  101223. }
  101224. });
  101225. if (animatable) {
  101226. this._animatables.push(animatable);
  101227. }
  101228. };
  101229. /**
  101230. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  101231. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  101232. * frustum width.
  101233. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  101234. * to fully enclose the mesh in the viewing frustum.
  101235. */
  101236. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  101237. var size = maximumWorld.subtract(minimumWorld);
  101238. var boxVectorGlobalDiagonal = size.length();
  101239. var frustumSlope = this._getFrustumSlope();
  101240. // Formula for setting distance
  101241. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  101242. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  101243. // Horizon distance
  101244. var radius = radiusWithoutFraming * this._radiusScale;
  101245. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  101246. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  101247. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  101248. var camera = this._attachedCamera;
  101249. if (!camera) {
  101250. return 0;
  101251. }
  101252. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  101253. // Don't exceed the requested limit
  101254. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  101255. }
  101256. // Don't exceed the upper radius limit
  101257. if (camera.upperRadiusLimit) {
  101258. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  101259. }
  101260. return distance;
  101261. };
  101262. /**
  101263. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  101264. * is automatically returned to its default position (expected to be above ground plane).
  101265. */
  101266. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  101267. var _this = this;
  101268. if (this._elevationReturnTime < 0) {
  101269. return;
  101270. }
  101271. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  101272. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  101273. var limitBeta = Math.PI * 0.5;
  101274. // Bring the camera back up if below the ground plane
  101275. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  101276. this._betaIsAnimating = true;
  101277. //Transition to new position
  101278. this.stopAllAnimations();
  101279. if (!this._betaTransition) {
  101280. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  101281. }
  101282. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  101283. _this._clearAnimationLocks();
  101284. _this.stopAllAnimations();
  101285. });
  101286. if (animatabe) {
  101287. this._animatables.push(animatabe);
  101288. }
  101289. }
  101290. };
  101291. /**
  101292. * Returns the frustum slope based on the canvas ratio and camera FOV
  101293. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  101294. */
  101295. FramingBehavior.prototype._getFrustumSlope = function () {
  101296. // Calculate the viewport ratio
  101297. // Aspect Ratio is Height/Width.
  101298. var camera = this._attachedCamera;
  101299. if (!camera) {
  101300. return BABYLON.Vector2.Zero();
  101301. }
  101302. var engine = camera.getScene().getEngine();
  101303. var aspectRatio = engine.getAspectRatio(camera);
  101304. // Camera FOV is the vertical field of view (top-bottom) in radians.
  101305. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  101306. var frustumSlopeY = Math.tan(camera.fov / 2);
  101307. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  101308. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  101309. // along the forward vector.
  101310. var frustumSlopeX = frustumSlopeY * aspectRatio;
  101311. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  101312. };
  101313. /**
  101314. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  101315. */
  101316. FramingBehavior.prototype._clearAnimationLocks = function () {
  101317. this._betaIsAnimating = false;
  101318. };
  101319. /**
  101320. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101321. */
  101322. FramingBehavior.prototype._applyUserInteraction = function () {
  101323. if (this.isUserIsMoving) {
  101324. this._lastInteractionTime = BABYLON.Tools.Now;
  101325. this.stopAllAnimations();
  101326. this._clearAnimationLocks();
  101327. }
  101328. };
  101329. /**
  101330. * Stops and removes all animations that have been applied to the camera
  101331. */
  101332. FramingBehavior.prototype.stopAllAnimations = function () {
  101333. if (this._attachedCamera) {
  101334. this._attachedCamera.animations = [];
  101335. }
  101336. while (this._animatables.length) {
  101337. if (this._animatables[0]) {
  101338. this._animatables[0].onAnimationEnd = null;
  101339. this._animatables[0].stop();
  101340. }
  101341. this._animatables.shift();
  101342. }
  101343. };
  101344. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  101345. /**
  101346. * Gets a value indicating if the user is moving the camera
  101347. */
  101348. get: function () {
  101349. if (!this._attachedCamera) {
  101350. return false;
  101351. }
  101352. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101353. this._attachedCamera.inertialBetaOffset !== 0 ||
  101354. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101355. this._attachedCamera.inertialPanningX !== 0 ||
  101356. this._attachedCamera.inertialPanningY !== 0 ||
  101357. this._isPointerDown;
  101358. },
  101359. enumerable: true,
  101360. configurable: true
  101361. });
  101362. /**
  101363. * The easing function used by animations
  101364. */
  101365. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  101366. /**
  101367. * The easing mode used by animations
  101368. */
  101369. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  101370. // Statics
  101371. /**
  101372. * The camera can move all the way towards the mesh.
  101373. */
  101374. FramingBehavior.IgnoreBoundsSizeMode = 0;
  101375. /**
  101376. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  101377. */
  101378. FramingBehavior.FitFrustumSidesMode = 1;
  101379. return FramingBehavior;
  101380. }());
  101381. BABYLON.FramingBehavior = FramingBehavior;
  101382. })(BABYLON || (BABYLON = {}));
  101383. //# sourceMappingURL=babylon.framingBehavior.js.map
  101384. var BABYLON;
  101385. (function (BABYLON) {
  101386. /**
  101387. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  101388. */
  101389. var BouncingBehavior = /** @class */ (function () {
  101390. function BouncingBehavior() {
  101391. /**
  101392. * The duration of the animation, in milliseconds
  101393. */
  101394. this.transitionDuration = 450;
  101395. /**
  101396. * Length of the distance animated by the transition when lower radius is reached
  101397. */
  101398. this.lowerRadiusTransitionRange = 2;
  101399. /**
  101400. * Length of the distance animated by the transition when upper radius is reached
  101401. */
  101402. this.upperRadiusTransitionRange = -2;
  101403. this._autoTransitionRange = false;
  101404. // Animations
  101405. this._radiusIsAnimating = false;
  101406. this._radiusBounceTransition = null;
  101407. this._animatables = new Array();
  101408. }
  101409. Object.defineProperty(BouncingBehavior.prototype, "name", {
  101410. get: function () {
  101411. return "Bouncing";
  101412. },
  101413. enumerable: true,
  101414. configurable: true
  101415. });
  101416. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  101417. /**
  101418. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  101419. */
  101420. get: function () {
  101421. return this._autoTransitionRange;
  101422. },
  101423. /**
  101424. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  101425. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  101426. */
  101427. set: function (value) {
  101428. var _this = this;
  101429. if (this._autoTransitionRange === value) {
  101430. return;
  101431. }
  101432. this._autoTransitionRange = value;
  101433. var camera = this._attachedCamera;
  101434. if (!camera) {
  101435. return;
  101436. }
  101437. if (value) {
  101438. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  101439. if (!mesh) {
  101440. return;
  101441. }
  101442. mesh.computeWorldMatrix(true);
  101443. var diagonal = mesh.getBoundingInfo().diagonalLength;
  101444. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  101445. _this.upperRadiusTransitionRange = diagonal * 0.05;
  101446. });
  101447. }
  101448. else if (this._onMeshTargetChangedObserver) {
  101449. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101450. }
  101451. },
  101452. enumerable: true,
  101453. configurable: true
  101454. });
  101455. BouncingBehavior.prototype.init = function () {
  101456. // Do notihng
  101457. };
  101458. BouncingBehavior.prototype.attach = function (camera) {
  101459. var _this = this;
  101460. this._attachedCamera = camera;
  101461. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101462. if (!_this._attachedCamera) {
  101463. return;
  101464. }
  101465. // Add the bounce animation to the lower radius limit
  101466. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  101467. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  101468. }
  101469. // Add the bounce animation to the upper radius limit
  101470. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  101471. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  101472. }
  101473. });
  101474. };
  101475. BouncingBehavior.prototype.detach = function () {
  101476. if (!this._attachedCamera) {
  101477. return;
  101478. }
  101479. if (this._onAfterCheckInputsObserver) {
  101480. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101481. }
  101482. if (this._onMeshTargetChangedObserver) {
  101483. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101484. }
  101485. this._attachedCamera = null;
  101486. };
  101487. /**
  101488. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  101489. * @param radiusLimit The limit to check against.
  101490. * @return Bool to indicate if at limit.
  101491. */
  101492. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  101493. if (!this._attachedCamera) {
  101494. return false;
  101495. }
  101496. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  101497. return true;
  101498. }
  101499. return false;
  101500. };
  101501. /**
  101502. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  101503. * @param radiusDelta The delta by which to animate to. Can be negative.
  101504. */
  101505. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  101506. var _this = this;
  101507. if (!this._attachedCamera) {
  101508. return;
  101509. }
  101510. if (!this._radiusBounceTransition) {
  101511. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  101512. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  101513. }
  101514. // Prevent zoom until bounce has completed
  101515. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  101516. this._attachedCamera.wheelPrecision = Infinity;
  101517. this._attachedCamera.inertialRadiusOffset = 0;
  101518. // Animate to the radius limit
  101519. this.stopAllAnimations();
  101520. this._radiusIsAnimating = true;
  101521. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  101522. if (animatable) {
  101523. this._animatables.push(animatable);
  101524. }
  101525. };
  101526. /**
  101527. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  101528. */
  101529. BouncingBehavior.prototype._clearAnimationLocks = function () {
  101530. this._radiusIsAnimating = false;
  101531. if (this._attachedCamera) {
  101532. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  101533. }
  101534. };
  101535. /**
  101536. * Stops and removes all animations that have been applied to the camera
  101537. */
  101538. BouncingBehavior.prototype.stopAllAnimations = function () {
  101539. if (this._attachedCamera) {
  101540. this._attachedCamera.animations = [];
  101541. }
  101542. while (this._animatables.length) {
  101543. this._animatables[0].onAnimationEnd = null;
  101544. this._animatables[0].stop();
  101545. this._animatables.shift();
  101546. }
  101547. };
  101548. /**
  101549. * The easing function used by animations
  101550. */
  101551. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  101552. /**
  101553. * The easing mode used by animations
  101554. */
  101555. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  101556. return BouncingBehavior;
  101557. }());
  101558. BABYLON.BouncingBehavior = BouncingBehavior;
  101559. })(BABYLON || (BABYLON = {}));
  101560. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  101561. var BABYLON;
  101562. (function (BABYLON) {
  101563. var AutoRotationBehavior = /** @class */ (function () {
  101564. function AutoRotationBehavior() {
  101565. this._zoomStopsAnimation = false;
  101566. this._idleRotationSpeed = 0.05;
  101567. this._idleRotationWaitTime = 2000;
  101568. this._idleRotationSpinupTime = 2000;
  101569. this._isPointerDown = false;
  101570. this._lastFrameTime = null;
  101571. this._lastInteractionTime = -Infinity;
  101572. this._cameraRotationSpeed = 0;
  101573. this._lastFrameRadius = 0;
  101574. }
  101575. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  101576. get: function () {
  101577. return "AutoRotation";
  101578. },
  101579. enumerable: true,
  101580. configurable: true
  101581. });
  101582. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  101583. /**
  101584. * Gets the flag that indicates if user zooming should stop animation.
  101585. */
  101586. get: function () {
  101587. return this._zoomStopsAnimation;
  101588. },
  101589. /**
  101590. * Sets the flag that indicates if user zooming should stop animation.
  101591. */
  101592. set: function (flag) {
  101593. this._zoomStopsAnimation = flag;
  101594. },
  101595. enumerable: true,
  101596. configurable: true
  101597. });
  101598. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  101599. /**
  101600. * Gets the default speed at which the camera rotates around the model.
  101601. */
  101602. get: function () {
  101603. return this._idleRotationSpeed;
  101604. },
  101605. /**
  101606. * Sets the default speed at which the camera rotates around the model.
  101607. */
  101608. set: function (speed) {
  101609. this._idleRotationSpeed = speed;
  101610. },
  101611. enumerable: true,
  101612. configurable: true
  101613. });
  101614. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  101615. /**
  101616. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  101617. */
  101618. get: function () {
  101619. return this._idleRotationWaitTime;
  101620. },
  101621. /**
  101622. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  101623. */
  101624. set: function (time) {
  101625. this._idleRotationWaitTime = time;
  101626. },
  101627. enumerable: true,
  101628. configurable: true
  101629. });
  101630. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  101631. /**
  101632. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101633. */
  101634. get: function () {
  101635. return this._idleRotationSpinupTime;
  101636. },
  101637. /**
  101638. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101639. */
  101640. set: function (time) {
  101641. this._idleRotationSpinupTime = time;
  101642. },
  101643. enumerable: true,
  101644. configurable: true
  101645. });
  101646. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  101647. /**
  101648. * Gets a value indicating if the camera is currently rotating because of this behavior
  101649. */
  101650. get: function () {
  101651. return Math.abs(this._cameraRotationSpeed) > 0;
  101652. },
  101653. enumerable: true,
  101654. configurable: true
  101655. });
  101656. AutoRotationBehavior.prototype.init = function () {
  101657. // Do notihng
  101658. };
  101659. AutoRotationBehavior.prototype.attach = function (camera) {
  101660. var _this = this;
  101661. this._attachedCamera = camera;
  101662. var scene = this._attachedCamera.getScene();
  101663. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101664. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101665. _this._isPointerDown = true;
  101666. return;
  101667. }
  101668. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101669. _this._isPointerDown = false;
  101670. }
  101671. });
  101672. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101673. var now = BABYLON.Tools.Now;
  101674. var dt = 0;
  101675. if (_this._lastFrameTime != null) {
  101676. dt = now - _this._lastFrameTime;
  101677. }
  101678. _this._lastFrameTime = now;
  101679. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101680. _this._applyUserInteraction();
  101681. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  101682. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  101683. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  101684. // Step camera rotation by rotation speed
  101685. if (_this._attachedCamera) {
  101686. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  101687. }
  101688. });
  101689. };
  101690. AutoRotationBehavior.prototype.detach = function () {
  101691. if (!this._attachedCamera) {
  101692. return;
  101693. }
  101694. var scene = this._attachedCamera.getScene();
  101695. if (this._onPrePointerObservableObserver) {
  101696. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101697. }
  101698. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101699. this._attachedCamera = null;
  101700. };
  101701. /**
  101702. * Returns true if user is scrolling.
  101703. * @return true if user is scrolling.
  101704. */
  101705. AutoRotationBehavior.prototype._userIsZooming = function () {
  101706. if (!this._attachedCamera) {
  101707. return false;
  101708. }
  101709. return this._attachedCamera.inertialRadiusOffset !== 0;
  101710. };
  101711. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  101712. if (!this._attachedCamera) {
  101713. return false;
  101714. }
  101715. var zoomHasHitLimit = false;
  101716. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  101717. zoomHasHitLimit = true;
  101718. }
  101719. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  101720. this._lastFrameRadius = this._attachedCamera.radius;
  101721. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  101722. };
  101723. /**
  101724. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101725. */
  101726. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  101727. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  101728. this._lastInteractionTime = BABYLON.Tools.Now;
  101729. }
  101730. };
  101731. // Tools
  101732. AutoRotationBehavior.prototype._userIsMoving = function () {
  101733. if (!this._attachedCamera) {
  101734. return false;
  101735. }
  101736. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101737. this._attachedCamera.inertialBetaOffset !== 0 ||
  101738. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101739. this._attachedCamera.inertialPanningX !== 0 ||
  101740. this._attachedCamera.inertialPanningY !== 0 ||
  101741. this._isPointerDown;
  101742. };
  101743. return AutoRotationBehavior;
  101744. }());
  101745. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  101746. })(BABYLON || (BABYLON = {}));
  101747. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  101748. var BABYLON;
  101749. (function (BABYLON) {
  101750. var NullEngineOptions = /** @class */ (function () {
  101751. function NullEngineOptions() {
  101752. this.renderWidth = 512;
  101753. this.renderHeight = 256;
  101754. this.textureSize = 512;
  101755. this.deterministicLockstep = false;
  101756. this.lockstepMaxSteps = 4;
  101757. }
  101758. return NullEngineOptions;
  101759. }());
  101760. BABYLON.NullEngineOptions = NullEngineOptions;
  101761. /**
  101762. * The null engine class provides support for headless version of babylon.js.
  101763. * This can be used in server side scenario or for testing purposes
  101764. */
  101765. var NullEngine = /** @class */ (function (_super) {
  101766. __extends(NullEngine, _super);
  101767. function NullEngine(options) {
  101768. if (options === void 0) { options = new NullEngineOptions(); }
  101769. var _this = _super.call(this, null) || this;
  101770. if (options.deterministicLockstep === undefined) {
  101771. options.deterministicLockstep = false;
  101772. }
  101773. if (options.lockstepMaxSteps === undefined) {
  101774. options.lockstepMaxSteps = 4;
  101775. }
  101776. _this._options = options;
  101777. // Init caps
  101778. // We consider we are on a webgl1 capable device
  101779. _this._caps = new BABYLON.EngineCapabilities();
  101780. _this._caps.maxTexturesImageUnits = 16;
  101781. _this._caps.maxVertexTextureImageUnits = 16;
  101782. _this._caps.maxTextureSize = 512;
  101783. _this._caps.maxCubemapTextureSize = 512;
  101784. _this._caps.maxRenderTextureSize = 512;
  101785. _this._caps.maxVertexAttribs = 16;
  101786. _this._caps.maxVaryingVectors = 16;
  101787. _this._caps.maxFragmentUniformVectors = 16;
  101788. _this._caps.maxVertexUniformVectors = 16;
  101789. // Extensions
  101790. _this._caps.standardDerivatives = false;
  101791. _this._caps.astc = null;
  101792. _this._caps.s3tc = null;
  101793. _this._caps.pvrtc = null;
  101794. _this._caps.etc1 = null;
  101795. _this._caps.etc2 = null;
  101796. _this._caps.textureAnisotropicFilterExtension = null;
  101797. _this._caps.maxAnisotropy = 0;
  101798. _this._caps.uintIndices = false;
  101799. _this._caps.fragmentDepthSupported = false;
  101800. _this._caps.highPrecisionShaderSupported = true;
  101801. _this._caps.colorBufferFloat = false;
  101802. _this._caps.textureFloat = false;
  101803. _this._caps.textureFloatLinearFiltering = false;
  101804. _this._caps.textureFloatRender = false;
  101805. _this._caps.textureHalfFloat = false;
  101806. _this._caps.textureHalfFloatLinearFiltering = false;
  101807. _this._caps.textureHalfFloatRender = false;
  101808. _this._caps.textureLOD = false;
  101809. _this._caps.drawBuffersExtension = false;
  101810. _this._caps.depthTextureExtension = false;
  101811. _this._caps.vertexArrayObject = false;
  101812. _this._caps.instancedArrays = false;
  101813. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  101814. // Wrappers
  101815. if (typeof URL === "undefined") {
  101816. URL = {
  101817. createObjectURL: function () { },
  101818. revokeObjectURL: function () { }
  101819. };
  101820. }
  101821. if (typeof Blob === "undefined") {
  101822. Blob = function () { };
  101823. }
  101824. return _this;
  101825. }
  101826. NullEngine.prototype.isDeterministicLockStep = function () {
  101827. return this._options.deterministicLockstep;
  101828. };
  101829. NullEngine.prototype.getLockstepMaxSteps = function () {
  101830. return this._options.lockstepMaxSteps;
  101831. };
  101832. NullEngine.prototype.getHardwareScalingLevel = function () {
  101833. return 1.0;
  101834. };
  101835. NullEngine.prototype.createVertexBuffer = function (vertices) {
  101836. return {
  101837. capacity: 0,
  101838. references: 1,
  101839. is32Bits: false
  101840. };
  101841. };
  101842. NullEngine.prototype.createIndexBuffer = function (indices) {
  101843. return {
  101844. capacity: 0,
  101845. references: 1,
  101846. is32Bits: false
  101847. };
  101848. };
  101849. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  101850. if (stencil === void 0) { stencil = false; }
  101851. };
  101852. NullEngine.prototype.getRenderWidth = function (useScreen) {
  101853. if (useScreen === void 0) { useScreen = false; }
  101854. if (!useScreen && this._currentRenderTarget) {
  101855. return this._currentRenderTarget.width;
  101856. }
  101857. return this._options.renderWidth;
  101858. };
  101859. NullEngine.prototype.getRenderHeight = function (useScreen) {
  101860. if (useScreen === void 0) { useScreen = false; }
  101861. if (!useScreen && this._currentRenderTarget) {
  101862. return this._currentRenderTarget.height;
  101863. }
  101864. return this._options.renderHeight;
  101865. };
  101866. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  101867. this._cachedViewport = viewport;
  101868. };
  101869. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  101870. return {
  101871. transformFeedback: null,
  101872. __SPECTOR_rebuildProgram: null
  101873. };
  101874. };
  101875. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  101876. return [];
  101877. };
  101878. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  101879. return [];
  101880. };
  101881. NullEngine.prototype.bindSamplers = function (effect) {
  101882. this._currentEffect = null;
  101883. };
  101884. NullEngine.prototype.enableEffect = function (effect) {
  101885. this._currentEffect = effect;
  101886. if (effect.onBind) {
  101887. effect.onBind(effect);
  101888. }
  101889. if (effect._onBindObservable) {
  101890. effect._onBindObservable.notifyObservers(effect);
  101891. }
  101892. };
  101893. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  101894. if (zOffset === void 0) { zOffset = 0; }
  101895. if (reverseSide === void 0) { reverseSide = false; }
  101896. };
  101897. NullEngine.prototype.setIntArray = function (uniform, array) {
  101898. };
  101899. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  101900. };
  101901. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  101902. };
  101903. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  101904. };
  101905. NullEngine.prototype.setFloatArray = function (uniform, array) {
  101906. };
  101907. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  101908. };
  101909. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  101910. };
  101911. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  101912. };
  101913. NullEngine.prototype.setArray = function (uniform, array) {
  101914. };
  101915. NullEngine.prototype.setArray2 = function (uniform, array) {
  101916. };
  101917. NullEngine.prototype.setArray3 = function (uniform, array) {
  101918. };
  101919. NullEngine.prototype.setArray4 = function (uniform, array) {
  101920. };
  101921. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  101922. };
  101923. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  101924. };
  101925. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  101926. };
  101927. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  101928. };
  101929. NullEngine.prototype.setFloat = function (uniform, value) {
  101930. };
  101931. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  101932. };
  101933. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  101934. };
  101935. NullEngine.prototype.setBool = function (uniform, bool) {
  101936. };
  101937. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  101938. };
  101939. NullEngine.prototype.setColor3 = function (uniform, color3) {
  101940. };
  101941. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  101942. };
  101943. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  101944. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  101945. if (this._alphaMode === mode) {
  101946. return;
  101947. }
  101948. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  101949. if (!noDepthWriteChange) {
  101950. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  101951. }
  101952. this._alphaMode = mode;
  101953. };
  101954. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  101955. };
  101956. NullEngine.prototype.wipeCaches = function (bruteForce) {
  101957. if (this.preventCacheWipeBetweenFrames) {
  101958. return;
  101959. }
  101960. this.resetTextureCache();
  101961. this._currentEffect = null;
  101962. if (bruteForce) {
  101963. this._currentProgram = null;
  101964. this._stencilState.reset();
  101965. this._depthCullingState.reset();
  101966. this._alphaState.reset();
  101967. }
  101968. this._cachedVertexBuffers = null;
  101969. this._cachedIndexBuffer = null;
  101970. this._cachedEffectForVertexBuffers = null;
  101971. };
  101972. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  101973. };
  101974. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  101975. };
  101976. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  101977. };
  101978. NullEngine.prototype._createTexture = function () {
  101979. return {};
  101980. };
  101981. NullEngine.prototype._releaseTexture = function (texture) {
  101982. };
  101983. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  101984. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101985. if (onLoad === void 0) { onLoad = null; }
  101986. if (onError === void 0) { onError = null; }
  101987. if (buffer === void 0) { buffer = null; }
  101988. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  101989. var url = String(urlArg);
  101990. texture.url = url;
  101991. texture.generateMipMaps = !noMipmap;
  101992. texture.samplingMode = samplingMode;
  101993. texture.invertY = invertY;
  101994. texture.baseWidth = this._options.textureSize;
  101995. texture.baseHeight = this._options.textureSize;
  101996. texture.width = this._options.textureSize;
  101997. texture.height = this._options.textureSize;
  101998. if (format) {
  101999. texture.format = format;
  102000. }
  102001. texture.isReady = true;
  102002. if (onLoad) {
  102003. onLoad();
  102004. }
  102005. this._internalTexturesCache.push(texture);
  102006. return texture;
  102007. };
  102008. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  102009. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  102010. if (options !== undefined && typeof options === "object") {
  102011. fullOptions.generateMipMaps = options.generateMipMaps;
  102012. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  102013. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  102014. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  102015. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  102016. }
  102017. else {
  102018. fullOptions.generateMipMaps = options;
  102019. fullOptions.generateDepthBuffer = true;
  102020. fullOptions.generateStencilBuffer = false;
  102021. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102022. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  102023. }
  102024. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  102025. var width = size.width || size;
  102026. var height = size.height || size;
  102027. texture._depthStencilBuffer = {};
  102028. texture._framebuffer = {};
  102029. texture.baseWidth = width;
  102030. texture.baseHeight = height;
  102031. texture.width = width;
  102032. texture.height = height;
  102033. texture.isReady = true;
  102034. texture.samples = 1;
  102035. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  102036. texture.samplingMode = fullOptions.samplingMode;
  102037. texture.type = fullOptions.type;
  102038. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  102039. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  102040. this._internalTexturesCache.push(texture);
  102041. return texture;
  102042. };
  102043. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  102044. texture.samplingMode = samplingMode;
  102045. };
  102046. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  102047. if (this._currentRenderTarget) {
  102048. this.unBindFramebuffer(this._currentRenderTarget);
  102049. }
  102050. this._currentRenderTarget = texture;
  102051. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  102052. if (this._cachedViewport && !forceFullscreenViewport) {
  102053. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  102054. }
  102055. };
  102056. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  102057. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  102058. this._currentRenderTarget = null;
  102059. if (onBeforeUnbind) {
  102060. if (texture._MSAAFramebuffer) {
  102061. this._currentFramebuffer = texture._framebuffer;
  102062. }
  102063. onBeforeUnbind();
  102064. }
  102065. this._currentFramebuffer = null;
  102066. };
  102067. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  102068. var vbo = {
  102069. capacity: 1,
  102070. references: 1,
  102071. is32Bits: false
  102072. };
  102073. return vbo;
  102074. };
  102075. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  102076. if (premulAlpha === void 0) { premulAlpha = false; }
  102077. };
  102078. /**
  102079. * Get the current error code of the webGL context
  102080. * @returns the error code
  102081. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  102082. */
  102083. NullEngine.prototype.getError = function () {
  102084. return 0;
  102085. };
  102086. /** @hidden */
  102087. NullEngine.prototype._getUnpackAlignement = function () {
  102088. return 1;
  102089. };
  102090. /** @hidden */
  102091. NullEngine.prototype._unpackFlipY = function (value) {
  102092. };
  102093. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  102094. if (offset === void 0) { offset = 0; }
  102095. };
  102096. /**
  102097. * Updates a dynamic vertex buffer.
  102098. * @param vertexBuffer the vertex buffer to update
  102099. * @param data the data used to update the vertex buffer
  102100. * @param byteOffset the byte offset of the data (optional)
  102101. * @param byteLength the byte length of the data (optional)
  102102. */
  102103. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  102104. };
  102105. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  102106. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  102107. this._boundTexturesCache[this._activeChannel] = texture;
  102108. return true;
  102109. }
  102110. return false;
  102111. };
  102112. NullEngine.prototype._bindTexture = function (channel, texture) {
  102113. if (channel < 0) {
  102114. return;
  102115. }
  102116. this._bindTextureDirectly(0, texture);
  102117. };
  102118. NullEngine.prototype._releaseBuffer = function (buffer) {
  102119. buffer.references--;
  102120. if (buffer.references === 0) {
  102121. return true;
  102122. }
  102123. return false;
  102124. };
  102125. NullEngine.prototype.releaseEffects = function () {
  102126. };
  102127. NullEngine.prototype.displayLoadingUI = function () {
  102128. };
  102129. NullEngine.prototype.hideLoadingUI = function () {
  102130. };
  102131. /** @hidden */
  102132. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  102133. if (faceIndex === void 0) { faceIndex = 0; }
  102134. if (lod === void 0) { lod = 0; }
  102135. };
  102136. /** @hidden */
  102137. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  102138. if (faceIndex === void 0) { faceIndex = 0; }
  102139. if (lod === void 0) { lod = 0; }
  102140. };
  102141. /** @hidden */
  102142. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  102143. if (faceIndex === void 0) { faceIndex = 0; }
  102144. if (lod === void 0) { lod = 0; }
  102145. };
  102146. /** @hidden */
  102147. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  102148. if (faceIndex === void 0) { faceIndex = 0; }
  102149. if (lod === void 0) { lod = 0; }
  102150. };
  102151. return NullEngine;
  102152. }(BABYLON.Engine));
  102153. BABYLON.NullEngine = NullEngine;
  102154. })(BABYLON || (BABYLON = {}));
  102155. //# sourceMappingURL=babylon.nullEngine.js.map
  102156. var BABYLON;
  102157. (function (BABYLON) {
  102158. /**
  102159. * This class can be used to get instrumentation data from a Babylon engine
  102160. */
  102161. var EngineInstrumentation = /** @class */ (function () {
  102162. function EngineInstrumentation(engine) {
  102163. this.engine = engine;
  102164. this._captureGPUFrameTime = false;
  102165. this._gpuFrameTime = new BABYLON.PerfCounter();
  102166. this._captureShaderCompilationTime = false;
  102167. this._shaderCompilationTime = new BABYLON.PerfCounter();
  102168. // Observers
  102169. this._onBeginFrameObserver = null;
  102170. this._onEndFrameObserver = null;
  102171. this._onBeforeShaderCompilationObserver = null;
  102172. this._onAfterShaderCompilationObserver = null;
  102173. }
  102174. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  102175. // Properties
  102176. /**
  102177. * Gets the perf counter used for GPU frame time
  102178. */
  102179. get: function () {
  102180. return this._gpuFrameTime;
  102181. },
  102182. enumerable: true,
  102183. configurable: true
  102184. });
  102185. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  102186. /**
  102187. * Gets the GPU frame time capture status
  102188. */
  102189. get: function () {
  102190. return this._captureGPUFrameTime;
  102191. },
  102192. /**
  102193. * Enable or disable the GPU frame time capture
  102194. */
  102195. set: function (value) {
  102196. var _this = this;
  102197. if (value === this._captureGPUFrameTime) {
  102198. return;
  102199. }
  102200. this._captureGPUFrameTime = value;
  102201. if (value) {
  102202. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  102203. if (!_this._gpuFrameTimeToken) {
  102204. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  102205. }
  102206. });
  102207. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  102208. if (!_this._gpuFrameTimeToken) {
  102209. return;
  102210. }
  102211. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  102212. if (time > -1) {
  102213. _this._gpuFrameTimeToken = null;
  102214. _this._gpuFrameTime.fetchNewFrame();
  102215. _this._gpuFrameTime.addCount(time, true);
  102216. }
  102217. });
  102218. }
  102219. else {
  102220. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  102221. this._onBeginFrameObserver = null;
  102222. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  102223. this._onEndFrameObserver = null;
  102224. }
  102225. },
  102226. enumerable: true,
  102227. configurable: true
  102228. });
  102229. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  102230. /**
  102231. * Gets the perf counter used for shader compilation time
  102232. */
  102233. get: function () {
  102234. return this._shaderCompilationTime;
  102235. },
  102236. enumerable: true,
  102237. configurable: true
  102238. });
  102239. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  102240. /**
  102241. * Gets the shader compilation time capture status
  102242. */
  102243. get: function () {
  102244. return this._captureShaderCompilationTime;
  102245. },
  102246. /**
  102247. * Enable or disable the shader compilation time capture
  102248. */
  102249. set: function (value) {
  102250. var _this = this;
  102251. if (value === this._captureShaderCompilationTime) {
  102252. return;
  102253. }
  102254. this._captureShaderCompilationTime = value;
  102255. if (value) {
  102256. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  102257. _this._shaderCompilationTime.fetchNewFrame();
  102258. _this._shaderCompilationTime.beginMonitoring();
  102259. });
  102260. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  102261. _this._shaderCompilationTime.endMonitoring();
  102262. });
  102263. }
  102264. else {
  102265. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  102266. this._onBeforeShaderCompilationObserver = null;
  102267. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  102268. this._onAfterShaderCompilationObserver = null;
  102269. }
  102270. },
  102271. enumerable: true,
  102272. configurable: true
  102273. });
  102274. EngineInstrumentation.prototype.dispose = function () {
  102275. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  102276. this._onBeginFrameObserver = null;
  102277. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  102278. this._onEndFrameObserver = null;
  102279. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  102280. this._onBeforeShaderCompilationObserver = null;
  102281. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  102282. this._onAfterShaderCompilationObserver = null;
  102283. this.engine = null;
  102284. };
  102285. return EngineInstrumentation;
  102286. }());
  102287. BABYLON.EngineInstrumentation = EngineInstrumentation;
  102288. })(BABYLON || (BABYLON = {}));
  102289. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  102290. var BABYLON;
  102291. (function (BABYLON) {
  102292. /**
  102293. * This class can be used to get instrumentation data from a Babylon engine
  102294. */
  102295. var SceneInstrumentation = /** @class */ (function () {
  102296. function SceneInstrumentation(scene) {
  102297. var _this = this;
  102298. this.scene = scene;
  102299. this._captureActiveMeshesEvaluationTime = false;
  102300. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  102301. this._captureRenderTargetsRenderTime = false;
  102302. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  102303. this._captureFrameTime = false;
  102304. this._frameTime = new BABYLON.PerfCounter();
  102305. this._captureRenderTime = false;
  102306. this._renderTime = new BABYLON.PerfCounter();
  102307. this._captureInterFrameTime = false;
  102308. this._interFrameTime = new BABYLON.PerfCounter();
  102309. this._captureParticlesRenderTime = false;
  102310. this._particlesRenderTime = new BABYLON.PerfCounter();
  102311. this._captureSpritesRenderTime = false;
  102312. this._spritesRenderTime = new BABYLON.PerfCounter();
  102313. this._capturePhysicsTime = false;
  102314. this._physicsTime = new BABYLON.PerfCounter();
  102315. this._captureAnimationsTime = false;
  102316. this._animationsTime = new BABYLON.PerfCounter();
  102317. this._captureCameraRenderTime = false;
  102318. this._cameraRenderTime = new BABYLON.PerfCounter();
  102319. // Observers
  102320. this._onBeforeActiveMeshesEvaluationObserver = null;
  102321. this._onAfterActiveMeshesEvaluationObserver = null;
  102322. this._onBeforeRenderTargetsRenderObserver = null;
  102323. this._onAfterRenderTargetsRenderObserver = null;
  102324. this._onAfterRenderObserver = null;
  102325. this._onBeforeDrawPhaseObserver = null;
  102326. this._onAfterDrawPhaseObserver = null;
  102327. this._onBeforeAnimationsObserver = null;
  102328. this._onBeforeParticlesRenderingObserver = null;
  102329. this._onAfterParticlesRenderingObserver = null;
  102330. this._onBeforeSpritesRenderingObserver = null;
  102331. this._onAfterSpritesRenderingObserver = null;
  102332. this._onBeforePhysicsObserver = null;
  102333. this._onAfterPhysicsObserver = null;
  102334. this._onAfterAnimationsObserver = null;
  102335. this._onBeforeCameraRenderObserver = null;
  102336. this._onAfterCameraRenderObserver = null;
  102337. // Before render
  102338. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  102339. if (_this._captureActiveMeshesEvaluationTime) {
  102340. _this._activeMeshesEvaluationTime.fetchNewFrame();
  102341. }
  102342. if (_this._captureRenderTargetsRenderTime) {
  102343. _this._renderTargetsRenderTime.fetchNewFrame();
  102344. }
  102345. if (_this._captureFrameTime) {
  102346. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  102347. _this._frameTime.beginMonitoring();
  102348. }
  102349. if (_this._captureInterFrameTime) {
  102350. _this._interFrameTime.endMonitoring();
  102351. }
  102352. if (_this._captureParticlesRenderTime) {
  102353. _this._particlesRenderTime.fetchNewFrame();
  102354. }
  102355. if (_this._captureSpritesRenderTime) {
  102356. _this._spritesRenderTime.fetchNewFrame();
  102357. }
  102358. if (_this._captureAnimationsTime) {
  102359. _this._animationsTime.beginMonitoring();
  102360. }
  102361. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  102362. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  102363. });
  102364. // After render
  102365. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  102366. if (_this._captureFrameTime) {
  102367. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  102368. _this._frameTime.endMonitoring();
  102369. }
  102370. if (_this._captureRenderTime) {
  102371. _this._renderTime.endMonitoring(false);
  102372. }
  102373. if (_this._captureInterFrameTime) {
  102374. _this._interFrameTime.beginMonitoring();
  102375. }
  102376. });
  102377. }
  102378. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  102379. // Properties
  102380. /**
  102381. * Gets the perf counter used for active meshes evaluation time
  102382. */
  102383. get: function () {
  102384. return this._activeMeshesEvaluationTime;
  102385. },
  102386. enumerable: true,
  102387. configurable: true
  102388. });
  102389. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  102390. /**
  102391. * Gets the active meshes evaluation time capture status
  102392. */
  102393. get: function () {
  102394. return this._captureActiveMeshesEvaluationTime;
  102395. },
  102396. /**
  102397. * Enable or disable the active meshes evaluation time capture
  102398. */
  102399. set: function (value) {
  102400. var _this = this;
  102401. if (value === this._captureActiveMeshesEvaluationTime) {
  102402. return;
  102403. }
  102404. this._captureActiveMeshesEvaluationTime = value;
  102405. if (value) {
  102406. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  102407. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  102408. _this._activeMeshesEvaluationTime.beginMonitoring();
  102409. });
  102410. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  102411. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  102412. _this._activeMeshesEvaluationTime.endMonitoring();
  102413. });
  102414. }
  102415. else {
  102416. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102417. this._onBeforeActiveMeshesEvaluationObserver = null;
  102418. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102419. this._onAfterActiveMeshesEvaluationObserver = null;
  102420. }
  102421. },
  102422. enumerable: true,
  102423. configurable: true
  102424. });
  102425. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  102426. /**
  102427. * Gets the perf counter used for render targets render time
  102428. */
  102429. get: function () {
  102430. return this._renderTargetsRenderTime;
  102431. },
  102432. enumerable: true,
  102433. configurable: true
  102434. });
  102435. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  102436. /**
  102437. * Gets the render targets render time capture status
  102438. */
  102439. get: function () {
  102440. return this._captureRenderTargetsRenderTime;
  102441. },
  102442. /**
  102443. * Enable or disable the render targets render time capture
  102444. */
  102445. set: function (value) {
  102446. var _this = this;
  102447. if (value === this._captureRenderTargetsRenderTime) {
  102448. return;
  102449. }
  102450. this._captureRenderTargetsRenderTime = value;
  102451. if (value) {
  102452. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  102453. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  102454. _this._renderTargetsRenderTime.beginMonitoring();
  102455. });
  102456. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  102457. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  102458. _this._renderTargetsRenderTime.endMonitoring(false);
  102459. });
  102460. }
  102461. else {
  102462. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102463. this._onBeforeRenderTargetsRenderObserver = null;
  102464. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102465. this._onAfterRenderTargetsRenderObserver = null;
  102466. }
  102467. },
  102468. enumerable: true,
  102469. configurable: true
  102470. });
  102471. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  102472. /**
  102473. * Gets the perf counter used for particles render time
  102474. */
  102475. get: function () {
  102476. return this._particlesRenderTime;
  102477. },
  102478. enumerable: true,
  102479. configurable: true
  102480. });
  102481. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  102482. /**
  102483. * Gets the particles render time capture status
  102484. */
  102485. get: function () {
  102486. return this._captureParticlesRenderTime;
  102487. },
  102488. /**
  102489. * Enable or disable the particles render time capture
  102490. */
  102491. set: function (value) {
  102492. var _this = this;
  102493. if (value === this._captureParticlesRenderTime) {
  102494. return;
  102495. }
  102496. this._captureParticlesRenderTime = value;
  102497. if (value) {
  102498. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  102499. BABYLON.Tools.StartPerformanceCounter("Particles");
  102500. _this._particlesRenderTime.beginMonitoring();
  102501. });
  102502. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  102503. BABYLON.Tools.EndPerformanceCounter("Particles");
  102504. _this._particlesRenderTime.endMonitoring(false);
  102505. });
  102506. }
  102507. else {
  102508. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102509. this._onBeforeParticlesRenderingObserver = null;
  102510. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102511. this._onAfterParticlesRenderingObserver = null;
  102512. }
  102513. },
  102514. enumerable: true,
  102515. configurable: true
  102516. });
  102517. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  102518. /**
  102519. * Gets the perf counter used for sprites render time
  102520. */
  102521. get: function () {
  102522. return this._spritesRenderTime;
  102523. },
  102524. enumerable: true,
  102525. configurable: true
  102526. });
  102527. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  102528. /**
  102529. * Gets the sprites render time capture status
  102530. */
  102531. get: function () {
  102532. return this._captureSpritesRenderTime;
  102533. },
  102534. /**
  102535. * Enable or disable the sprites render time capture
  102536. */
  102537. set: function (value) {
  102538. var _this = this;
  102539. if (value === this._captureSpritesRenderTime) {
  102540. return;
  102541. }
  102542. this._captureSpritesRenderTime = value;
  102543. if (value) {
  102544. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  102545. BABYLON.Tools.StartPerformanceCounter("Sprites");
  102546. _this._spritesRenderTime.beginMonitoring();
  102547. });
  102548. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  102549. BABYLON.Tools.EndPerformanceCounter("Sprites");
  102550. _this._spritesRenderTime.endMonitoring(false);
  102551. });
  102552. }
  102553. else {
  102554. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102555. this._onBeforeSpritesRenderingObserver = null;
  102556. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102557. this._onAfterSpritesRenderingObserver = null;
  102558. }
  102559. },
  102560. enumerable: true,
  102561. configurable: true
  102562. });
  102563. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  102564. /**
  102565. * Gets the perf counter used for physics time
  102566. */
  102567. get: function () {
  102568. return this._physicsTime;
  102569. },
  102570. enumerable: true,
  102571. configurable: true
  102572. });
  102573. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  102574. /**
  102575. * Gets the physics time capture status
  102576. */
  102577. get: function () {
  102578. return this._capturePhysicsTime;
  102579. },
  102580. /**
  102581. * Enable or disable the physics time capture
  102582. */
  102583. set: function (value) {
  102584. var _this = this;
  102585. if (value === this._capturePhysicsTime) {
  102586. return;
  102587. }
  102588. this._capturePhysicsTime = value;
  102589. if (value) {
  102590. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  102591. BABYLON.Tools.StartPerformanceCounter("Physics");
  102592. _this._physicsTime.beginMonitoring();
  102593. });
  102594. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  102595. BABYLON.Tools.EndPerformanceCounter("Physics");
  102596. _this._physicsTime.endMonitoring();
  102597. });
  102598. }
  102599. else {
  102600. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102601. this._onBeforePhysicsObserver = null;
  102602. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102603. this._onAfterPhysicsObserver = null;
  102604. }
  102605. },
  102606. enumerable: true,
  102607. configurable: true
  102608. });
  102609. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  102610. /**
  102611. * Gets the perf counter used for animations time
  102612. */
  102613. get: function () {
  102614. return this._animationsTime;
  102615. },
  102616. enumerable: true,
  102617. configurable: true
  102618. });
  102619. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  102620. /**
  102621. * Gets the animations time capture status
  102622. */
  102623. get: function () {
  102624. return this._captureAnimationsTime;
  102625. },
  102626. /**
  102627. * Enable or disable the animations time capture
  102628. */
  102629. set: function (value) {
  102630. var _this = this;
  102631. if (value === this._captureAnimationsTime) {
  102632. return;
  102633. }
  102634. this._captureAnimationsTime = value;
  102635. if (value) {
  102636. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  102637. _this._animationsTime.endMonitoring();
  102638. });
  102639. }
  102640. else {
  102641. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102642. this._onAfterAnimationsObserver = null;
  102643. }
  102644. },
  102645. enumerable: true,
  102646. configurable: true
  102647. });
  102648. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  102649. /**
  102650. * Gets the perf counter used for frame time capture
  102651. */
  102652. get: function () {
  102653. return this._frameTime;
  102654. },
  102655. enumerable: true,
  102656. configurable: true
  102657. });
  102658. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  102659. /**
  102660. * Gets the frame time capture status
  102661. */
  102662. get: function () {
  102663. return this._captureFrameTime;
  102664. },
  102665. /**
  102666. * Enable or disable the frame time capture
  102667. */
  102668. set: function (value) {
  102669. this._captureFrameTime = value;
  102670. },
  102671. enumerable: true,
  102672. configurable: true
  102673. });
  102674. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  102675. /**
  102676. * Gets the perf counter used for inter-frames time capture
  102677. */
  102678. get: function () {
  102679. return this._interFrameTime;
  102680. },
  102681. enumerable: true,
  102682. configurable: true
  102683. });
  102684. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  102685. /**
  102686. * Gets the inter-frames time capture status
  102687. */
  102688. get: function () {
  102689. return this._captureInterFrameTime;
  102690. },
  102691. /**
  102692. * Enable or disable the inter-frames time capture
  102693. */
  102694. set: function (value) {
  102695. this._captureInterFrameTime = value;
  102696. },
  102697. enumerable: true,
  102698. configurable: true
  102699. });
  102700. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  102701. /**
  102702. * Gets the perf counter used for render time capture
  102703. */
  102704. get: function () {
  102705. return this._renderTime;
  102706. },
  102707. enumerable: true,
  102708. configurable: true
  102709. });
  102710. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  102711. /**
  102712. * Gets the render time capture status
  102713. */
  102714. get: function () {
  102715. return this._captureRenderTime;
  102716. },
  102717. /**
  102718. * Enable or disable the render time capture
  102719. */
  102720. set: function (value) {
  102721. var _this = this;
  102722. if (value === this._captureRenderTime) {
  102723. return;
  102724. }
  102725. this._captureRenderTime = value;
  102726. if (value) {
  102727. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  102728. _this._renderTime.beginMonitoring();
  102729. BABYLON.Tools.StartPerformanceCounter("Main render");
  102730. });
  102731. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  102732. _this._renderTime.endMonitoring(false);
  102733. BABYLON.Tools.EndPerformanceCounter("Main render");
  102734. });
  102735. }
  102736. else {
  102737. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102738. this._onBeforeDrawPhaseObserver = null;
  102739. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102740. this._onAfterDrawPhaseObserver = null;
  102741. }
  102742. },
  102743. enumerable: true,
  102744. configurable: true
  102745. });
  102746. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  102747. /**
  102748. * Gets the perf counter used for camera render time capture
  102749. */
  102750. get: function () {
  102751. return this._cameraRenderTime;
  102752. },
  102753. enumerable: true,
  102754. configurable: true
  102755. });
  102756. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  102757. /**
  102758. * Gets the camera render time capture status
  102759. */
  102760. get: function () {
  102761. return this._captureCameraRenderTime;
  102762. },
  102763. /**
  102764. * Enable or disable the camera render time capture
  102765. */
  102766. set: function (value) {
  102767. var _this = this;
  102768. if (value === this._captureCameraRenderTime) {
  102769. return;
  102770. }
  102771. this._captureCameraRenderTime = value;
  102772. if (value) {
  102773. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  102774. _this._cameraRenderTime.beginMonitoring();
  102775. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  102776. });
  102777. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  102778. _this._cameraRenderTime.endMonitoring(false);
  102779. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  102780. });
  102781. }
  102782. else {
  102783. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102784. this._onBeforeCameraRenderObserver = null;
  102785. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102786. this._onAfterCameraRenderObserver = null;
  102787. }
  102788. },
  102789. enumerable: true,
  102790. configurable: true
  102791. });
  102792. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  102793. /**
  102794. * Gets the perf counter used for draw calls
  102795. */
  102796. get: function () {
  102797. return this.scene.getEngine()._drawCalls;
  102798. },
  102799. enumerable: true,
  102800. configurable: true
  102801. });
  102802. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  102803. /**
  102804. * Gets the perf counter used for texture collisions
  102805. */
  102806. get: function () {
  102807. return this.scene.getEngine()._textureCollisions;
  102808. },
  102809. enumerable: true,
  102810. configurable: true
  102811. });
  102812. SceneInstrumentation.prototype.dispose = function () {
  102813. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102814. this._onAfterRenderObserver = null;
  102815. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102816. this._onBeforeActiveMeshesEvaluationObserver = null;
  102817. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102818. this._onAfterActiveMeshesEvaluationObserver = null;
  102819. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102820. this._onBeforeRenderTargetsRenderObserver = null;
  102821. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102822. this._onAfterRenderTargetsRenderObserver = null;
  102823. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  102824. this._onBeforeAnimationsObserver = null;
  102825. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102826. this._onBeforeParticlesRenderingObserver = null;
  102827. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102828. this._onAfterParticlesRenderingObserver = null;
  102829. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102830. this._onBeforeSpritesRenderingObserver = null;
  102831. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102832. this._onAfterSpritesRenderingObserver = null;
  102833. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102834. this._onBeforeDrawPhaseObserver = null;
  102835. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102836. this._onAfterDrawPhaseObserver = null;
  102837. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102838. this._onBeforePhysicsObserver = null;
  102839. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102840. this._onAfterPhysicsObserver = null;
  102841. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102842. this._onAfterAnimationsObserver = null;
  102843. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102844. this._onBeforeCameraRenderObserver = null;
  102845. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102846. this._onAfterCameraRenderObserver = null;
  102847. this.scene = null;
  102848. };
  102849. return SceneInstrumentation;
  102850. }());
  102851. BABYLON.SceneInstrumentation = SceneInstrumentation;
  102852. })(BABYLON || (BABYLON = {}));
  102853. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  102854. var BABYLON;
  102855. (function (BABYLON) {
  102856. /**
  102857. * @hidden
  102858. **/
  102859. var _TimeToken = /** @class */ (function () {
  102860. function _TimeToken() {
  102861. this._timeElapsedQueryEnded = false;
  102862. }
  102863. return _TimeToken;
  102864. }());
  102865. BABYLON._TimeToken = _TimeToken;
  102866. })(BABYLON || (BABYLON = {}));
  102867. //# sourceMappingURL=babylon.timeToken.js.map
  102868. var BABYLON;
  102869. (function (BABYLON) {
  102870. /**
  102871. * Background material defines definition.
  102872. * @hidden Mainly internal Use
  102873. */
  102874. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  102875. __extends(BackgroundMaterialDefines, _super);
  102876. /**
  102877. * Constructor of the defines.
  102878. */
  102879. function BackgroundMaterialDefines() {
  102880. var _this = _super.call(this) || this;
  102881. /**
  102882. * True if the diffuse texture is in use.
  102883. */
  102884. _this.DIFFUSE = false;
  102885. /**
  102886. * The direct UV channel to use.
  102887. */
  102888. _this.DIFFUSEDIRECTUV = 0;
  102889. /**
  102890. * True if the diffuse texture is in gamma space.
  102891. */
  102892. _this.GAMMADIFFUSE = false;
  102893. /**
  102894. * True if the diffuse texture has opacity in the alpha channel.
  102895. */
  102896. _this.DIFFUSEHASALPHA = false;
  102897. /**
  102898. * True if you want the material to fade to transparent at grazing angle.
  102899. */
  102900. _this.OPACITYFRESNEL = false;
  102901. /**
  102902. * True if an extra blur needs to be added in the reflection.
  102903. */
  102904. _this.REFLECTIONBLUR = false;
  102905. /**
  102906. * True if you want the material to fade to reflection at grazing angle.
  102907. */
  102908. _this.REFLECTIONFRESNEL = false;
  102909. /**
  102910. * True if you want the material to falloff as far as you move away from the scene center.
  102911. */
  102912. _this.REFLECTIONFALLOFF = false;
  102913. /**
  102914. * False if the current Webgl implementation does not support the texture lod extension.
  102915. */
  102916. _this.TEXTURELODSUPPORT = false;
  102917. /**
  102918. * True to ensure the data are premultiplied.
  102919. */
  102920. _this.PREMULTIPLYALPHA = false;
  102921. /**
  102922. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  102923. */
  102924. _this.USERGBCOLOR = false;
  102925. /**
  102926. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  102927. * stays aligned with the desired configuration.
  102928. */
  102929. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  102930. /**
  102931. * True to add noise in order to reduce the banding effect.
  102932. */
  102933. _this.NOISE = false;
  102934. /**
  102935. * is the reflection texture in BGR color scheme?
  102936. * Mainly used to solve a bug in ios10 video tag
  102937. */
  102938. _this.REFLECTIONBGR = false;
  102939. _this.IMAGEPROCESSING = false;
  102940. _this.VIGNETTE = false;
  102941. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  102942. _this.VIGNETTEBLENDMODEOPAQUE = false;
  102943. _this.TONEMAPPING = false;
  102944. _this.CONTRAST = false;
  102945. _this.COLORCURVES = false;
  102946. _this.COLORGRADING = false;
  102947. _this.COLORGRADING3D = false;
  102948. _this.SAMPLER3DGREENDEPTH = false;
  102949. _this.SAMPLER3DBGRMAP = false;
  102950. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  102951. _this.EXPOSURE = false;
  102952. // Reflection.
  102953. _this.REFLECTION = false;
  102954. _this.REFLECTIONMAP_3D = false;
  102955. _this.REFLECTIONMAP_SPHERICAL = false;
  102956. _this.REFLECTIONMAP_PLANAR = false;
  102957. _this.REFLECTIONMAP_CUBIC = false;
  102958. _this.REFLECTIONMAP_PROJECTION = false;
  102959. _this.REFLECTIONMAP_SKYBOX = false;
  102960. _this.REFLECTIONMAP_EXPLICIT = false;
  102961. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102962. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102963. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102964. _this.INVERTCUBICMAP = false;
  102965. _this.REFLECTIONMAP_OPPOSITEZ = false;
  102966. _this.LODINREFLECTIONALPHA = false;
  102967. _this.GAMMAREFLECTION = false;
  102968. _this.RGBDREFLECTION = false;
  102969. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  102970. // Default BJS.
  102971. _this.MAINUV1 = false;
  102972. _this.MAINUV2 = false;
  102973. _this.UV1 = false;
  102974. _this.UV2 = false;
  102975. _this.CLIPPLANE = false;
  102976. _this.POINTSIZE = false;
  102977. _this.FOG = false;
  102978. _this.NORMAL = false;
  102979. _this.NUM_BONE_INFLUENCERS = 0;
  102980. _this.BonesPerMesh = 0;
  102981. _this.INSTANCES = false;
  102982. _this.SHADOWFLOAT = false;
  102983. _this.rebuild();
  102984. return _this;
  102985. }
  102986. return BackgroundMaterialDefines;
  102987. }(BABYLON.MaterialDefines));
  102988. /**
  102989. * Background material used to create an efficient environement around your scene.
  102990. */
  102991. var BackgroundMaterial = /** @class */ (function (_super) {
  102992. __extends(BackgroundMaterial, _super);
  102993. /**
  102994. * Instantiates a Background Material in the given scene
  102995. * @param name The friendly name of the material
  102996. * @param scene The scene to add the material to
  102997. */
  102998. function BackgroundMaterial(name, scene) {
  102999. var _this = _super.call(this, name, scene) || this;
  103000. /**
  103001. * Key light Color (multiply against the environement texture)
  103002. */
  103003. _this.primaryColor = BABYLON.Color3.White();
  103004. _this._primaryColorShadowLevel = 0;
  103005. _this._primaryColorHighlightLevel = 0;
  103006. /**
  103007. * Reflection Texture used in the material.
  103008. * Should be author in a specific way for the best result (refer to the documentation).
  103009. */
  103010. _this.reflectionTexture = null;
  103011. /**
  103012. * Reflection Texture level of blur.
  103013. *
  103014. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  103015. * texture twice.
  103016. */
  103017. _this.reflectionBlur = 0;
  103018. /**
  103019. * Diffuse Texture used in the material.
  103020. * Should be author in a specific way for the best result (refer to the documentation).
  103021. */
  103022. _this.diffuseTexture = null;
  103023. _this._shadowLights = null;
  103024. /**
  103025. * Specify the list of lights casting shadow on the material.
  103026. * All scene shadow lights will be included if null.
  103027. */
  103028. _this.shadowLights = null;
  103029. /**
  103030. * Helps adjusting the shadow to a softer level if required.
  103031. * 0 means black shadows and 1 means no shadows.
  103032. */
  103033. _this.shadowLevel = 0;
  103034. /**
  103035. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  103036. * It is usually zero but might be interesting to modify according to your setup.
  103037. */
  103038. _this.sceneCenter = BABYLON.Vector3.Zero();
  103039. /**
  103040. * This helps specifying that the material is falling off to the sky box at grazing angle.
  103041. * This helps ensuring a nice transition when the camera goes under the ground.
  103042. */
  103043. _this.opacityFresnel = true;
  103044. /**
  103045. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  103046. * This helps adding a mirror texture on the ground.
  103047. */
  103048. _this.reflectionFresnel = false;
  103049. /**
  103050. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  103051. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  103052. */
  103053. _this.reflectionFalloffDistance = 0.0;
  103054. /**
  103055. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  103056. */
  103057. _this.reflectionAmount = 1.0;
  103058. /**
  103059. * This specifies the weight of the reflection at grazing angle.
  103060. */
  103061. _this.reflectionReflectance0 = 0.05;
  103062. /**
  103063. * This specifies the weight of the reflection at a perpendicular point of view.
  103064. */
  103065. _this.reflectionReflectance90 = 0.5;
  103066. /**
  103067. * Helps to directly use the maps channels instead of their level.
  103068. */
  103069. _this.useRGBColor = true;
  103070. /**
  103071. * This helps reducing the banding effect that could occur on the background.
  103072. */
  103073. _this.enableNoise = false;
  103074. _this._fovMultiplier = 1.0;
  103075. /**
  103076. * Enable the FOV adjustment feature controlled by fovMultiplier.
  103077. */
  103078. _this.useEquirectangularFOV = false;
  103079. _this._maxSimultaneousLights = 4;
  103080. /**
  103081. * Number of Simultaneous lights allowed on the material.
  103082. */
  103083. _this.maxSimultaneousLights = 4;
  103084. /**
  103085. * Keep track of the image processing observer to allow dispose and replace.
  103086. */
  103087. _this._imageProcessingObserver = null;
  103088. /**
  103089. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  103090. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  103091. */
  103092. _this.switchToBGR = false;
  103093. // Temp values kept as cache in the material.
  103094. _this._renderTargets = new BABYLON.SmartArray(16);
  103095. _this._reflectionControls = BABYLON.Vector4.Zero();
  103096. _this._white = BABYLON.Color3.White();
  103097. _this._primaryShadowColor = BABYLON.Color3.Black();
  103098. _this._primaryHighlightColor = BABYLON.Color3.Black();
  103099. // Setup the default processing configuration to the scene.
  103100. _this._attachImageProcessingConfiguration(null);
  103101. _this.getRenderTargetTextures = function () {
  103102. _this._renderTargets.reset();
  103103. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  103104. _this._renderTargets.push(_this._diffuseTexture);
  103105. }
  103106. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  103107. _this._renderTargets.push(_this._reflectionTexture);
  103108. }
  103109. return _this._renderTargets;
  103110. };
  103111. return _this;
  103112. }
  103113. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  103114. /**
  103115. * Experimental Internal Use Only.
  103116. *
  103117. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  103118. * This acts as a helper to set the primary color to a more "human friendly" value.
  103119. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  103120. * output color as close as possible from the chosen value.
  103121. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  103122. * part of lighting setup.)
  103123. */
  103124. get: function () {
  103125. return this.__perceptualColor;
  103126. },
  103127. set: function (value) {
  103128. this.__perceptualColor = value;
  103129. this._computePrimaryColorFromPerceptualColor();
  103130. this._markAllSubMeshesAsLightsDirty();
  103131. },
  103132. enumerable: true,
  103133. configurable: true
  103134. });
  103135. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  103136. /**
  103137. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  103138. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  103139. */
  103140. get: function () {
  103141. return this._primaryColorShadowLevel;
  103142. },
  103143. set: function (value) {
  103144. this._primaryColorShadowLevel = value;
  103145. this._computePrimaryColors();
  103146. this._markAllSubMeshesAsLightsDirty();
  103147. },
  103148. enumerable: true,
  103149. configurable: true
  103150. });
  103151. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  103152. /**
  103153. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  103154. * The primary color is used at the level chosen to define what the white area would look.
  103155. */
  103156. get: function () {
  103157. return this._primaryColorHighlightLevel;
  103158. },
  103159. set: function (value) {
  103160. this._primaryColorHighlightLevel = value;
  103161. this._computePrimaryColors();
  103162. this._markAllSubMeshesAsLightsDirty();
  103163. },
  103164. enumerable: true,
  103165. configurable: true
  103166. });
  103167. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  103168. /**
  103169. * Sets the reflection reflectance fresnel values according to the default standard
  103170. * empirically know to work well :-)
  103171. */
  103172. set: function (value) {
  103173. var reflectionWeight = value;
  103174. if (reflectionWeight < 0.5) {
  103175. reflectionWeight = reflectionWeight * 2.0;
  103176. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  103177. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  103178. }
  103179. else {
  103180. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  103181. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  103182. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  103183. }
  103184. },
  103185. enumerable: true,
  103186. configurable: true
  103187. });
  103188. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  103189. /**
  103190. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103191. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  103192. * Recommended to be keep at 1.0 except for special cases.
  103193. */
  103194. get: function () {
  103195. return this._fovMultiplier;
  103196. },
  103197. set: function (value) {
  103198. if (isNaN(value)) {
  103199. value = 1.0;
  103200. }
  103201. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  103202. },
  103203. enumerable: true,
  103204. configurable: true
  103205. });
  103206. /**
  103207. * Attaches a new image processing configuration to the PBR Material.
  103208. * @param configuration (if null the scene configuration will be use)
  103209. */
  103210. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  103211. var _this = this;
  103212. if (configuration === this._imageProcessingConfiguration) {
  103213. return;
  103214. }
  103215. // Detaches observer.
  103216. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103217. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103218. }
  103219. // Pick the scene configuration if needed.
  103220. if (!configuration) {
  103221. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  103222. }
  103223. else {
  103224. this._imageProcessingConfiguration = configuration;
  103225. }
  103226. // Attaches observer.
  103227. if (this._imageProcessingConfiguration) {
  103228. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  103229. _this._computePrimaryColorFromPerceptualColor();
  103230. _this._markAllSubMeshesAsImageProcessingDirty();
  103231. });
  103232. }
  103233. };
  103234. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  103235. /**
  103236. * Gets the image processing configuration used either in this material.
  103237. */
  103238. get: function () {
  103239. return this._imageProcessingConfiguration;
  103240. },
  103241. /**
  103242. * Sets the Default image processing configuration used either in the this material.
  103243. *
  103244. * If sets to null, the scene one is in use.
  103245. */
  103246. set: function (value) {
  103247. this._attachImageProcessingConfiguration(value);
  103248. // Ensure the effect will be rebuilt.
  103249. this._markAllSubMeshesAsTexturesDirty();
  103250. },
  103251. enumerable: true,
  103252. configurable: true
  103253. });
  103254. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  103255. /**
  103256. * Gets wether the color curves effect is enabled.
  103257. */
  103258. get: function () {
  103259. return this.imageProcessingConfiguration.colorCurvesEnabled;
  103260. },
  103261. /**
  103262. * Sets wether the color curves effect is enabled.
  103263. */
  103264. set: function (value) {
  103265. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  103266. },
  103267. enumerable: true,
  103268. configurable: true
  103269. });
  103270. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  103271. /**
  103272. * Gets wether the color grading effect is enabled.
  103273. */
  103274. get: function () {
  103275. return this.imageProcessingConfiguration.colorGradingEnabled;
  103276. },
  103277. /**
  103278. * Gets wether the color grading effect is enabled.
  103279. */
  103280. set: function (value) {
  103281. this.imageProcessingConfiguration.colorGradingEnabled = value;
  103282. },
  103283. enumerable: true,
  103284. configurable: true
  103285. });
  103286. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  103287. /**
  103288. * Gets wether tonemapping is enabled or not.
  103289. */
  103290. get: function () {
  103291. return this._imageProcessingConfiguration.toneMappingEnabled;
  103292. },
  103293. /**
  103294. * Sets wether tonemapping is enabled or not
  103295. */
  103296. set: function (value) {
  103297. this._imageProcessingConfiguration.toneMappingEnabled = value;
  103298. },
  103299. enumerable: true,
  103300. configurable: true
  103301. });
  103302. ;
  103303. ;
  103304. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  103305. /**
  103306. * The camera exposure used on this material.
  103307. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  103308. * This corresponds to a photographic exposure.
  103309. */
  103310. get: function () {
  103311. return this._imageProcessingConfiguration.exposure;
  103312. },
  103313. /**
  103314. * The camera exposure used on this material.
  103315. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  103316. * This corresponds to a photographic exposure.
  103317. */
  103318. set: function (value) {
  103319. this._imageProcessingConfiguration.exposure = value;
  103320. },
  103321. enumerable: true,
  103322. configurable: true
  103323. });
  103324. ;
  103325. ;
  103326. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  103327. /**
  103328. * Gets The camera contrast used on this material.
  103329. */
  103330. get: function () {
  103331. return this._imageProcessingConfiguration.contrast;
  103332. },
  103333. /**
  103334. * Sets The camera contrast used on this material.
  103335. */
  103336. set: function (value) {
  103337. this._imageProcessingConfiguration.contrast = value;
  103338. },
  103339. enumerable: true,
  103340. configurable: true
  103341. });
  103342. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  103343. /**
  103344. * Gets the Color Grading 2D Lookup Texture.
  103345. */
  103346. get: function () {
  103347. return this._imageProcessingConfiguration.colorGradingTexture;
  103348. },
  103349. /**
  103350. * Sets the Color Grading 2D Lookup Texture.
  103351. */
  103352. set: function (value) {
  103353. this.imageProcessingConfiguration.colorGradingTexture = value;
  103354. },
  103355. enumerable: true,
  103356. configurable: true
  103357. });
  103358. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  103359. /**
  103360. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  103361. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  103362. * 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;
  103363. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  103364. */
  103365. get: function () {
  103366. return this.imageProcessingConfiguration.colorCurves;
  103367. },
  103368. /**
  103369. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  103370. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  103371. * 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;
  103372. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  103373. */
  103374. set: function (value) {
  103375. this.imageProcessingConfiguration.colorCurves = value;
  103376. },
  103377. enumerable: true,
  103378. configurable: true
  103379. });
  103380. /**
  103381. * The entire material has been created in order to prevent overdraw.
  103382. * @returns false
  103383. */
  103384. BackgroundMaterial.prototype.needAlphaTesting = function () {
  103385. return true;
  103386. };
  103387. /**
  103388. * The entire material has been created in order to prevent overdraw.
  103389. * @returns true if blending is enable
  103390. */
  103391. BackgroundMaterial.prototype.needAlphaBlending = function () {
  103392. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  103393. };
  103394. /**
  103395. * Checks wether the material is ready to be rendered for a given mesh.
  103396. * @param mesh The mesh to render
  103397. * @param subMesh The submesh to check against
  103398. * @param useInstances Specify wether or not the material is used with instances
  103399. * @returns true if all the dependencies are ready (Textures, Effects...)
  103400. */
  103401. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  103402. var _this = this;
  103403. if (useInstances === void 0) { useInstances = false; }
  103404. if (subMesh.effect && this.isFrozen) {
  103405. if (this._wasPreviouslyReady) {
  103406. return true;
  103407. }
  103408. }
  103409. if (!subMesh._materialDefines) {
  103410. subMesh._materialDefines = new BackgroundMaterialDefines();
  103411. }
  103412. var scene = this.getScene();
  103413. var defines = subMesh._materialDefines;
  103414. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  103415. if (defines._renderId === scene.getRenderId()) {
  103416. return true;
  103417. }
  103418. }
  103419. var engine = scene.getEngine();
  103420. // Lights
  103421. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  103422. defines._needNormals = true;
  103423. // Textures
  103424. if (defines._areTexturesDirty) {
  103425. defines._needUVs = false;
  103426. if (scene.texturesEnabled) {
  103427. if (scene.getEngine().getCaps().textureLOD) {
  103428. defines.TEXTURELODSUPPORT = true;
  103429. }
  103430. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103431. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  103432. return false;
  103433. }
  103434. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  103435. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  103436. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  103437. defines.OPACITYFRESNEL = this._opacityFresnel;
  103438. }
  103439. else {
  103440. defines.DIFFUSE = false;
  103441. defines.DIFFUSEHASALPHA = false;
  103442. defines.GAMMADIFFUSE = false;
  103443. defines.OPACITYFRESNEL = false;
  103444. }
  103445. var reflectionTexture = this._reflectionTexture;
  103446. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103447. if (!reflectionTexture.isReadyOrNotBlocking()) {
  103448. return false;
  103449. }
  103450. defines.REFLECTION = true;
  103451. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  103452. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  103453. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  103454. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  103455. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  103456. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  103457. defines.REFLECTIONBGR = this.switchToBGR;
  103458. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  103459. defines.INVERTCUBICMAP = true;
  103460. }
  103461. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  103462. switch (reflectionTexture.coordinatesMode) {
  103463. case BABYLON.Texture.EXPLICIT_MODE:
  103464. defines.REFLECTIONMAP_EXPLICIT = true;
  103465. break;
  103466. case BABYLON.Texture.PLANAR_MODE:
  103467. defines.REFLECTIONMAP_PLANAR = true;
  103468. break;
  103469. case BABYLON.Texture.PROJECTION_MODE:
  103470. defines.REFLECTIONMAP_PROJECTION = true;
  103471. break;
  103472. case BABYLON.Texture.SKYBOX_MODE:
  103473. defines.REFLECTIONMAP_SKYBOX = true;
  103474. break;
  103475. case BABYLON.Texture.SPHERICAL_MODE:
  103476. defines.REFLECTIONMAP_SPHERICAL = true;
  103477. break;
  103478. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  103479. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  103480. break;
  103481. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  103482. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  103483. break;
  103484. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  103485. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  103486. break;
  103487. case BABYLON.Texture.CUBIC_MODE:
  103488. case BABYLON.Texture.INVCUBIC_MODE:
  103489. default:
  103490. defines.REFLECTIONMAP_CUBIC = true;
  103491. break;
  103492. }
  103493. if (this.reflectionFresnel) {
  103494. defines.REFLECTIONFRESNEL = true;
  103495. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  103496. this._reflectionControls.x = this.reflectionAmount;
  103497. this._reflectionControls.y = this.reflectionReflectance0;
  103498. this._reflectionControls.z = this.reflectionReflectance90;
  103499. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  103500. }
  103501. else {
  103502. defines.REFLECTIONFRESNEL = false;
  103503. defines.REFLECTIONFALLOFF = false;
  103504. }
  103505. }
  103506. else {
  103507. defines.REFLECTION = false;
  103508. defines.REFLECTIONFRESNEL = false;
  103509. defines.REFLECTIONFALLOFF = false;
  103510. defines.REFLECTIONBLUR = false;
  103511. defines.REFLECTIONMAP_3D = false;
  103512. defines.REFLECTIONMAP_SPHERICAL = false;
  103513. defines.REFLECTIONMAP_PLANAR = false;
  103514. defines.REFLECTIONMAP_CUBIC = false;
  103515. defines.REFLECTIONMAP_PROJECTION = false;
  103516. defines.REFLECTIONMAP_SKYBOX = false;
  103517. defines.REFLECTIONMAP_EXPLICIT = false;
  103518. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  103519. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  103520. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  103521. defines.INVERTCUBICMAP = false;
  103522. defines.REFLECTIONMAP_OPPOSITEZ = false;
  103523. defines.LODINREFLECTIONALPHA = false;
  103524. defines.GAMMAREFLECTION = false;
  103525. defines.RGBDREFLECTION = false;
  103526. }
  103527. }
  103528. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  103529. defines.USERGBCOLOR = this._useRGBColor;
  103530. defines.NOISE = this._enableNoise;
  103531. }
  103532. if (defines._areLightsDirty) {
  103533. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  103534. }
  103535. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  103536. if (!this._imageProcessingConfiguration.isReady()) {
  103537. return false;
  103538. }
  103539. this._imageProcessingConfiguration.prepareDefines(defines);
  103540. }
  103541. // Misc.
  103542. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  103543. // Values that need to be evaluated on every frame
  103544. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  103545. // Attribs
  103546. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  103547. if (mesh) {
  103548. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103549. mesh.createNormals(true);
  103550. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  103551. }
  103552. }
  103553. }
  103554. // Get correct effect
  103555. if (defines.isDirty) {
  103556. defines.markAsProcessed();
  103557. scene.resetCachedMaterial();
  103558. // Fallbacks
  103559. var fallbacks = new BABYLON.EffectFallbacks();
  103560. if (defines.FOG) {
  103561. fallbacks.addFallback(0, "FOG");
  103562. }
  103563. if (defines.POINTSIZE) {
  103564. fallbacks.addFallback(1, "POINTSIZE");
  103565. }
  103566. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  103567. if (defines.NUM_BONE_INFLUENCERS > 0) {
  103568. fallbacks.addCPUSkinningFallback(0, mesh);
  103569. }
  103570. //Attributes
  103571. var attribs = [BABYLON.VertexBuffer.PositionKind];
  103572. if (defines.NORMAL) {
  103573. attribs.push(BABYLON.VertexBuffer.NormalKind);
  103574. }
  103575. if (defines.UV1) {
  103576. attribs.push(BABYLON.VertexBuffer.UVKind);
  103577. }
  103578. if (defines.UV2) {
  103579. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103580. }
  103581. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  103582. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  103583. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  103584. "vFogInfos", "vFogColor", "pointSize",
  103585. "vClipPlane", "mBones",
  103586. "vPrimaryColor", "vPrimaryColorShadow",
  103587. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  103588. "shadowLevel", "alpha",
  103589. "vBackgroundCenter", "vReflectionControl",
  103590. "vDiffuseInfos", "diffuseMatrix",
  103591. ];
  103592. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  103593. var uniformBuffers = ["Material", "Scene"];
  103594. if (BABYLON.ImageProcessingConfiguration) {
  103595. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  103596. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  103597. }
  103598. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  103599. uniformsNames: uniforms,
  103600. uniformBuffersNames: uniformBuffers,
  103601. samplers: samplers,
  103602. defines: defines,
  103603. maxSimultaneousLights: this._maxSimultaneousLights
  103604. });
  103605. var onCompiled = function (effect) {
  103606. if (_this.onCompiled) {
  103607. _this.onCompiled(effect);
  103608. }
  103609. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  103610. };
  103611. var join = defines.toString();
  103612. subMesh.setEffect(scene.getEngine().createEffect("background", {
  103613. attributes: attribs,
  103614. uniformsNames: uniforms,
  103615. uniformBuffersNames: uniformBuffers,
  103616. samplers: samplers,
  103617. defines: join,
  103618. fallbacks: fallbacks,
  103619. onCompiled: onCompiled,
  103620. onError: this.onError,
  103621. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  103622. }, engine), defines);
  103623. this.buildUniformLayout();
  103624. }
  103625. if (!subMesh.effect || !subMesh.effect.isReady()) {
  103626. return false;
  103627. }
  103628. defines._renderId = scene.getRenderId();
  103629. this._wasPreviouslyReady = true;
  103630. return true;
  103631. };
  103632. /**
  103633. * Compute the primary color according to the chosen perceptual color.
  103634. */
  103635. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  103636. if (!this.__perceptualColor) {
  103637. return;
  103638. }
  103639. this._primaryColor.copyFrom(this.__perceptualColor);
  103640. // Revert gamma space.
  103641. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  103642. // Revert image processing configuration.
  103643. if (this._imageProcessingConfiguration) {
  103644. // Revert Exposure.
  103645. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  103646. }
  103647. this._computePrimaryColors();
  103648. };
  103649. /**
  103650. * Compute the highlights and shadow colors according to their chosen levels.
  103651. */
  103652. BackgroundMaterial.prototype._computePrimaryColors = function () {
  103653. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  103654. return;
  103655. }
  103656. // Find the highlight color based on the configuration.
  103657. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  103658. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  103659. // Find the shadow color based on the configuration.
  103660. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  103661. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  103662. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  103663. };
  103664. /**
  103665. * Build the uniform buffer used in the material.
  103666. */
  103667. BackgroundMaterial.prototype.buildUniformLayout = function () {
  103668. // Order is important !
  103669. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  103670. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  103671. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  103672. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  103673. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  103674. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  103675. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  103676. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  103677. this._uniformBuffer.addUniform("pointSize", 1);
  103678. this._uniformBuffer.addUniform("shadowLevel", 1);
  103679. this._uniformBuffer.addUniform("alpha", 1);
  103680. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  103681. this._uniformBuffer.addUniform("vReflectionControl", 4);
  103682. this._uniformBuffer.create();
  103683. };
  103684. /**
  103685. * Unbind the material.
  103686. */
  103687. BackgroundMaterial.prototype.unbind = function () {
  103688. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  103689. this._uniformBuffer.setTexture("diffuseSampler", null);
  103690. }
  103691. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  103692. this._uniformBuffer.setTexture("reflectionSampler", null);
  103693. }
  103694. _super.prototype.unbind.call(this);
  103695. };
  103696. /**
  103697. * Bind only the world matrix to the material.
  103698. * @param world The world matrix to bind.
  103699. */
  103700. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  103701. this._activeEffect.setMatrix("world", world);
  103702. };
  103703. /**
  103704. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  103705. * @param world The world matrix to bind.
  103706. * @param subMesh The submesh to bind for.
  103707. */
  103708. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  103709. var scene = this.getScene();
  103710. var defines = subMesh._materialDefines;
  103711. if (!defines) {
  103712. return;
  103713. }
  103714. var effect = subMesh.effect;
  103715. if (!effect) {
  103716. return;
  103717. }
  103718. this._activeEffect = effect;
  103719. // Matrices
  103720. this.bindOnlyWorldMatrix(world);
  103721. // Bones
  103722. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  103723. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  103724. if (mustRebind) {
  103725. this._uniformBuffer.bindToEffect(effect, "Material");
  103726. this.bindViewProjection(effect);
  103727. var reflectionTexture = this._reflectionTexture;
  103728. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  103729. // Texture uniforms
  103730. if (scene.texturesEnabled) {
  103731. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103732. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  103733. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  103734. }
  103735. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103736. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  103737. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  103738. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  103739. }
  103740. }
  103741. if (this.shadowLevel > 0) {
  103742. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  103743. }
  103744. this._uniformBuffer.updateFloat("alpha", this.alpha);
  103745. // Point size
  103746. if (this.pointsCloud) {
  103747. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  103748. }
  103749. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  103750. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  103751. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  103752. }
  103753. else {
  103754. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  103755. }
  103756. }
  103757. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  103758. // Textures
  103759. if (scene.texturesEnabled) {
  103760. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103761. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  103762. }
  103763. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103764. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  103765. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103766. }
  103767. else if (!defines.REFLECTIONBLUR) {
  103768. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103769. }
  103770. else {
  103771. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  103772. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  103773. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  103774. }
  103775. if (defines.REFLECTIONFRESNEL) {
  103776. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  103777. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  103778. }
  103779. }
  103780. }
  103781. // Clip plane
  103782. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  103783. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  103784. }
  103785. if (mustRebind || !this.isFrozen) {
  103786. if (scene.lightsEnabled) {
  103787. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  103788. }
  103789. // View
  103790. this.bindView(effect);
  103791. // Fog
  103792. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  103793. // image processing
  103794. if (this._imageProcessingConfiguration) {
  103795. this._imageProcessingConfiguration.bind(this._activeEffect);
  103796. }
  103797. }
  103798. this._uniformBuffer.update();
  103799. this._afterBind(mesh, this._activeEffect);
  103800. };
  103801. /**
  103802. * Dispose the material.
  103803. * @param forceDisposeEffect Force disposal of the associated effect.
  103804. * @param forceDisposeTextures Force disposal of the associated textures.
  103805. */
  103806. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  103807. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  103808. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  103809. if (forceDisposeTextures) {
  103810. if (this.diffuseTexture) {
  103811. this.diffuseTexture.dispose();
  103812. }
  103813. if (this.reflectionTexture) {
  103814. this.reflectionTexture.dispose();
  103815. }
  103816. }
  103817. this._renderTargets.dispose();
  103818. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103819. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103820. }
  103821. _super.prototype.dispose.call(this, forceDisposeEffect);
  103822. };
  103823. /**
  103824. * Clones the material.
  103825. * @param name The cloned name.
  103826. * @returns The cloned material.
  103827. */
  103828. BackgroundMaterial.prototype.clone = function (name) {
  103829. var _this = this;
  103830. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  103831. };
  103832. /**
  103833. * Serializes the current material to its JSON representation.
  103834. * @returns The JSON representation.
  103835. */
  103836. BackgroundMaterial.prototype.serialize = function () {
  103837. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103838. serializationObject.customType = "BABYLON.BackgroundMaterial";
  103839. return serializationObject;
  103840. };
  103841. /**
  103842. * Gets the class name of the material
  103843. * @returns "BackgroundMaterial"
  103844. */
  103845. BackgroundMaterial.prototype.getClassName = function () {
  103846. return "BackgroundMaterial";
  103847. };
  103848. /**
  103849. * Parse a JSON input to create back a background material.
  103850. * @param source The JSON data to parse
  103851. * @param scene The scene to create the parsed material in
  103852. * @param rootUrl The root url of the assets the material depends upon
  103853. * @returns the instantiated BackgroundMaterial.
  103854. */
  103855. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  103856. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  103857. };
  103858. /**
  103859. * Standard reflectance value at parallel view angle.
  103860. */
  103861. BackgroundMaterial.StandardReflectance0 = 0.05;
  103862. /**
  103863. * Standard reflectance value at grazing angle.
  103864. */
  103865. BackgroundMaterial.StandardReflectance90 = 0.5;
  103866. __decorate([
  103867. BABYLON.serializeAsColor3()
  103868. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  103869. __decorate([
  103870. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103871. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  103872. __decorate([
  103873. BABYLON.serializeAsColor3()
  103874. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  103875. __decorate([
  103876. BABYLON.serialize()
  103877. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  103878. __decorate([
  103879. BABYLON.serialize()
  103880. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  103881. __decorate([
  103882. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103883. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  103884. __decorate([
  103885. BABYLON.serializeAsTexture()
  103886. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  103887. __decorate([
  103888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103889. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  103890. __decorate([
  103891. BABYLON.serialize()
  103892. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  103893. __decorate([
  103894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103895. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  103896. __decorate([
  103897. BABYLON.serializeAsTexture()
  103898. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  103899. __decorate([
  103900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103901. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  103902. __decorate([
  103903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103904. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  103905. __decorate([
  103906. BABYLON.serialize()
  103907. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  103908. __decorate([
  103909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103910. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  103911. __decorate([
  103912. BABYLON.serializeAsVector3()
  103913. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  103914. __decorate([
  103915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103916. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  103917. __decorate([
  103918. BABYLON.serialize()
  103919. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  103920. __decorate([
  103921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103922. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  103923. __decorate([
  103924. BABYLON.serialize()
  103925. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  103926. __decorate([
  103927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103928. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  103929. __decorate([
  103930. BABYLON.serialize()
  103931. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  103932. __decorate([
  103933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103934. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  103935. __decorate([
  103936. BABYLON.serialize()
  103937. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  103938. __decorate([
  103939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103940. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  103941. __decorate([
  103942. BABYLON.serialize()
  103943. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  103944. __decorate([
  103945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103946. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  103947. __decorate([
  103948. BABYLON.serialize()
  103949. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  103950. __decorate([
  103951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103952. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  103953. __decorate([
  103954. BABYLON.serialize()
  103955. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  103956. __decorate([
  103957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103958. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  103959. __decorate([
  103960. BABYLON.serialize()
  103961. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  103962. __decorate([
  103963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103964. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  103965. __decorate([
  103966. BABYLON.serialize()
  103967. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  103968. __decorate([
  103969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103970. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  103971. __decorate([
  103972. BABYLON.serializeAsImageProcessingConfiguration()
  103973. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  103974. return BackgroundMaterial;
  103975. }(BABYLON.PushMaterial));
  103976. BABYLON.BackgroundMaterial = BackgroundMaterial;
  103977. })(BABYLON || (BABYLON = {}));
  103978. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  103979. var __assign = (this && this.__assign) || Object.assign || function(t) {
  103980. for (var s, i = 1, n = arguments.length; i < n; i++) {
  103981. s = arguments[i];
  103982. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  103983. t[p] = s[p];
  103984. }
  103985. return t;
  103986. };
  103987. var BABYLON;
  103988. (function (BABYLON) {
  103989. /**
  103990. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  103991. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  103992. * It also helps with the default setup of your imageProcessing configuration.
  103993. */
  103994. var EnvironmentHelper = /** @class */ (function () {
  103995. /**
  103996. * constructor
  103997. * @param options
  103998. * @param scene The scene to add the material to
  103999. */
  104000. function EnvironmentHelper(options, scene) {
  104001. var _this = this;
  104002. this._errorHandler = function (message, exception) {
  104003. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  104004. };
  104005. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  104006. this._scene = scene;
  104007. this.onErrorObservable = new BABYLON.Observable();
  104008. this._setupBackground();
  104009. this._setupImageProcessing();
  104010. }
  104011. /**
  104012. * Creates the default options for the helper.
  104013. */
  104014. EnvironmentHelper._getDefaultOptions = function () {
  104015. return {
  104016. createGround: true,
  104017. groundSize: 15,
  104018. groundTexture: this._groundTextureCDNUrl,
  104019. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  104020. groundOpacity: 0.9,
  104021. enableGroundShadow: true,
  104022. groundShadowLevel: 0.5,
  104023. enableGroundMirror: false,
  104024. groundMirrorSizeRatio: 0.3,
  104025. groundMirrorBlurKernel: 64,
  104026. groundMirrorAmount: 1,
  104027. groundMirrorFresnelWeight: 1,
  104028. groundMirrorFallOffDistance: 0,
  104029. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  104030. groundYBias: 0.00001,
  104031. createSkybox: true,
  104032. skyboxSize: 20,
  104033. skyboxTexture: this._skyboxTextureCDNUrl,
  104034. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  104035. backgroundYRotation: 0,
  104036. sizeAuto: true,
  104037. rootPosition: BABYLON.Vector3.Zero(),
  104038. setupImageProcessing: true,
  104039. environmentTexture: this._environmentTextureCDNUrl,
  104040. cameraExposure: 0.8,
  104041. cameraContrast: 1.2,
  104042. toneMappingEnabled: true,
  104043. };
  104044. };
  104045. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  104046. /**
  104047. * Gets the root mesh created by the helper.
  104048. */
  104049. get: function () {
  104050. return this._rootMesh;
  104051. },
  104052. enumerable: true,
  104053. configurable: true
  104054. });
  104055. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  104056. /**
  104057. * Gets the skybox created by the helper.
  104058. */
  104059. get: function () {
  104060. return this._skybox;
  104061. },
  104062. enumerable: true,
  104063. configurable: true
  104064. });
  104065. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  104066. /**
  104067. * Gets the skybox texture created by the helper.
  104068. */
  104069. get: function () {
  104070. return this._skyboxTexture;
  104071. },
  104072. enumerable: true,
  104073. configurable: true
  104074. });
  104075. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  104076. /**
  104077. * Gets the skybox material created by the helper.
  104078. */
  104079. get: function () {
  104080. return this._skyboxMaterial;
  104081. },
  104082. enumerable: true,
  104083. configurable: true
  104084. });
  104085. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  104086. /**
  104087. * Gets the ground mesh created by the helper.
  104088. */
  104089. get: function () {
  104090. return this._ground;
  104091. },
  104092. enumerable: true,
  104093. configurable: true
  104094. });
  104095. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  104096. /**
  104097. * Gets the ground texture created by the helper.
  104098. */
  104099. get: function () {
  104100. return this._groundTexture;
  104101. },
  104102. enumerable: true,
  104103. configurable: true
  104104. });
  104105. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  104106. /**
  104107. * Gets the ground mirror created by the helper.
  104108. */
  104109. get: function () {
  104110. return this._groundMirror;
  104111. },
  104112. enumerable: true,
  104113. configurable: true
  104114. });
  104115. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  104116. /**
  104117. * Gets the ground mirror render list to helps pushing the meshes
  104118. * you wish in the ground reflection.
  104119. */
  104120. get: function () {
  104121. if (this._groundMirror) {
  104122. return this._groundMirror.renderList;
  104123. }
  104124. return null;
  104125. },
  104126. enumerable: true,
  104127. configurable: true
  104128. });
  104129. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  104130. /**
  104131. * Gets the ground material created by the helper.
  104132. */
  104133. get: function () {
  104134. return this._groundMaterial;
  104135. },
  104136. enumerable: true,
  104137. configurable: true
  104138. });
  104139. /**
  104140. * Updates the background according to the new options
  104141. * @param options
  104142. */
  104143. EnvironmentHelper.prototype.updateOptions = function (options) {
  104144. var newOptions = __assign({}, this._options, options);
  104145. if (this._ground && !newOptions.createGround) {
  104146. this._ground.dispose();
  104147. this._ground = null;
  104148. }
  104149. if (this._groundMaterial && !newOptions.createGround) {
  104150. this._groundMaterial.dispose();
  104151. this._groundMaterial = null;
  104152. }
  104153. if (this._groundTexture) {
  104154. if (this._options.groundTexture != newOptions.groundTexture) {
  104155. this._groundTexture.dispose();
  104156. this._groundTexture = null;
  104157. }
  104158. }
  104159. if (this._skybox && !newOptions.createSkybox) {
  104160. this._skybox.dispose();
  104161. this._skybox = null;
  104162. }
  104163. if (this._skyboxMaterial && !newOptions.createSkybox) {
  104164. this._skyboxMaterial.dispose();
  104165. this._skyboxMaterial = null;
  104166. }
  104167. if (this._skyboxTexture) {
  104168. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  104169. this._skyboxTexture.dispose();
  104170. this._skyboxTexture = null;
  104171. }
  104172. }
  104173. if (this._groundMirror && !newOptions.enableGroundMirror) {
  104174. this._groundMirror.dispose();
  104175. this._groundMirror = null;
  104176. }
  104177. if (this._scene.environmentTexture) {
  104178. if (this._options.environmentTexture != newOptions.environmentTexture) {
  104179. this._scene.environmentTexture.dispose();
  104180. }
  104181. }
  104182. this._options = newOptions;
  104183. this._setupBackground();
  104184. this._setupImageProcessing();
  104185. };
  104186. /**
  104187. * Sets the primary color of all the available elements.
  104188. * @param color the main color to affect to the ground and the background
  104189. */
  104190. EnvironmentHelper.prototype.setMainColor = function (color) {
  104191. if (this.groundMaterial) {
  104192. this.groundMaterial.primaryColor = color;
  104193. }
  104194. if (this.skyboxMaterial) {
  104195. this.skyboxMaterial.primaryColor = color;
  104196. }
  104197. if (this.groundMirror) {
  104198. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  104199. }
  104200. };
  104201. /**
  104202. * Setup the image processing according to the specified options.
  104203. */
  104204. EnvironmentHelper.prototype._setupImageProcessing = function () {
  104205. if (this._options.setupImageProcessing) {
  104206. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  104207. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  104208. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  104209. this._setupEnvironmentTexture();
  104210. }
  104211. };
  104212. /**
  104213. * Setup the environment texture according to the specified options.
  104214. */
  104215. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  104216. if (this._scene.environmentTexture) {
  104217. return;
  104218. }
  104219. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  104220. this._scene.environmentTexture = this._options.environmentTexture;
  104221. return;
  104222. }
  104223. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  104224. this._scene.environmentTexture = environmentTexture;
  104225. };
  104226. /**
  104227. * Setup the background according to the specified options.
  104228. */
  104229. EnvironmentHelper.prototype._setupBackground = function () {
  104230. if (!this._rootMesh) {
  104231. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  104232. }
  104233. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  104234. var sceneSize = this._getSceneSize();
  104235. if (this._options.createGround) {
  104236. this._setupGround(sceneSize);
  104237. this._setupGroundMaterial();
  104238. this._setupGroundDiffuseTexture();
  104239. if (this._options.enableGroundMirror) {
  104240. this._setupGroundMirrorTexture(sceneSize);
  104241. }
  104242. this._setupMirrorInGroundMaterial();
  104243. }
  104244. if (this._options.createSkybox) {
  104245. this._setupSkybox(sceneSize);
  104246. this._setupSkyboxMaterial();
  104247. this._setupSkyboxReflectionTexture();
  104248. }
  104249. this._rootMesh.position.x = sceneSize.rootPosition.x;
  104250. this._rootMesh.position.z = sceneSize.rootPosition.z;
  104251. this._rootMesh.position.y = sceneSize.rootPosition.y;
  104252. };
  104253. /**
  104254. * Get the scene sizes according to the setup.
  104255. */
  104256. EnvironmentHelper.prototype._getSceneSize = function () {
  104257. var _this = this;
  104258. var groundSize = this._options.groundSize;
  104259. var skyboxSize = this._options.skyboxSize;
  104260. var rootPosition = this._options.rootPosition;
  104261. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  104262. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  104263. }
  104264. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  104265. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  104266. });
  104267. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  104268. if (this._options.sizeAuto) {
  104269. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  104270. this._scene.activeCamera.upperRadiusLimit) {
  104271. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  104272. skyboxSize = groundSize;
  104273. }
  104274. var sceneDiagonalLenght = sceneDiagonal.length();
  104275. if (sceneDiagonalLenght > groundSize) {
  104276. groundSize = sceneDiagonalLenght * 2;
  104277. skyboxSize = groundSize;
  104278. }
  104279. // 10 % bigger.
  104280. groundSize *= 1.1;
  104281. skyboxSize *= 1.5;
  104282. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  104283. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  104284. }
  104285. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  104286. };
  104287. /**
  104288. * Setup the ground according to the specified options.
  104289. */
  104290. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  104291. var _this = this;
  104292. if (!this._ground || this._ground.isDisposed()) {
  104293. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  104294. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  104295. this._ground.parent = this._rootMesh;
  104296. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  104297. }
  104298. this._ground.receiveShadows = this._options.enableGroundShadow;
  104299. };
  104300. /**
  104301. * Setup the ground material according to the specified options.
  104302. */
  104303. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  104304. if (!this._groundMaterial) {
  104305. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  104306. }
  104307. this._groundMaterial.alpha = this._options.groundOpacity;
  104308. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  104309. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  104310. this._groundMaterial.primaryColor = this._options.groundColor;
  104311. this._groundMaterial.useRGBColor = false;
  104312. this._groundMaterial.enableNoise = true;
  104313. if (this._ground) {
  104314. this._ground.material = this._groundMaterial;
  104315. }
  104316. };
  104317. /**
  104318. * Setup the ground diffuse texture according to the specified options.
  104319. */
  104320. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  104321. if (!this._groundMaterial) {
  104322. return;
  104323. }
  104324. if (this._groundTexture) {
  104325. return;
  104326. }
  104327. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  104328. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  104329. return;
  104330. }
  104331. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  104332. diffuseTexture.gammaSpace = false;
  104333. diffuseTexture.hasAlpha = true;
  104334. this._groundMaterial.diffuseTexture = diffuseTexture;
  104335. };
  104336. /**
  104337. * Setup the ground mirror texture according to the specified options.
  104338. */
  104339. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  104340. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104341. if (!this._groundMirror) {
  104342. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  104343. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  104344. this._groundMirror.anisotropicFilteringLevel = 1;
  104345. this._groundMirror.wrapU = wrapping;
  104346. this._groundMirror.wrapV = wrapping;
  104347. this._groundMirror.gammaSpace = false;
  104348. if (this._groundMirror.renderList) {
  104349. for (var i = 0; i < this._scene.meshes.length; i++) {
  104350. var mesh = this._scene.meshes[i];
  104351. if (mesh !== this._ground &&
  104352. mesh !== this._skybox &&
  104353. mesh !== this._rootMesh) {
  104354. this._groundMirror.renderList.push(mesh);
  104355. }
  104356. }
  104357. }
  104358. }
  104359. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  104360. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  104361. };
  104362. /**
  104363. * Setup the ground to receive the mirror texture.
  104364. */
  104365. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  104366. if (this._groundMaterial) {
  104367. this._groundMaterial.reflectionTexture = this._groundMirror;
  104368. this._groundMaterial.reflectionFresnel = true;
  104369. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  104370. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  104371. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  104372. }
  104373. };
  104374. /**
  104375. * Setup the skybox according to the specified options.
  104376. */
  104377. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  104378. var _this = this;
  104379. if (!this._skybox || this._skybox.isDisposed()) {
  104380. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  104381. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  104382. }
  104383. this._skybox.parent = this._rootMesh;
  104384. };
  104385. /**
  104386. * Setup the skybox material according to the specified options.
  104387. */
  104388. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  104389. if (!this._skybox) {
  104390. return;
  104391. }
  104392. if (!this._skyboxMaterial) {
  104393. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  104394. }
  104395. this._skyboxMaterial.useRGBColor = false;
  104396. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  104397. this._skyboxMaterial.enableNoise = true;
  104398. this._skybox.material = this._skyboxMaterial;
  104399. };
  104400. /**
  104401. * Setup the skybox reflection texture according to the specified options.
  104402. */
  104403. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  104404. if (!this._skyboxMaterial) {
  104405. return;
  104406. }
  104407. if (this._skyboxTexture) {
  104408. return;
  104409. }
  104410. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  104411. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  104412. return;
  104413. }
  104414. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  104415. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  104416. this._skyboxTexture.gammaSpace = false;
  104417. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  104418. };
  104419. /**
  104420. * Dispose all the elements created by the Helper.
  104421. */
  104422. EnvironmentHelper.prototype.dispose = function () {
  104423. if (this._groundMaterial) {
  104424. this._groundMaterial.dispose(true, true);
  104425. }
  104426. if (this._skyboxMaterial) {
  104427. this._skyboxMaterial.dispose(true, true);
  104428. }
  104429. this._rootMesh.dispose(false);
  104430. };
  104431. /**
  104432. * Default ground texture URL.
  104433. */
  104434. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  104435. /**
  104436. * Default skybox texture URL.
  104437. */
  104438. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  104439. /**
  104440. * Default environment texture URL.
  104441. */
  104442. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  104443. return EnvironmentHelper;
  104444. }());
  104445. BABYLON.EnvironmentHelper = EnvironmentHelper;
  104446. })(BABYLON || (BABYLON = {}));
  104447. //# sourceMappingURL=babylon.environmentHelper.js.map
  104448. var BABYLON;
  104449. (function (BABYLON) {
  104450. /** Internal class used to store shapes for emitters */
  104451. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  104452. function ParticleSystemSetEmitterCreationOptions() {
  104453. }
  104454. return ParticleSystemSetEmitterCreationOptions;
  104455. }());
  104456. /**
  104457. * Represents a set of particle systems working together to create a specific effect
  104458. */
  104459. var ParticleSystemSet = /** @class */ (function () {
  104460. function ParticleSystemSet() {
  104461. /**
  104462. * Gets the particle system list
  104463. */
  104464. this.systems = new Array();
  104465. }
  104466. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  104467. /**
  104468. * Gets the emitter node used with this set
  104469. */
  104470. get: function () {
  104471. return this._emitterNode;
  104472. },
  104473. enumerable: true,
  104474. configurable: true
  104475. });
  104476. /**
  104477. * Creates a new emitter mesh as a sphere
  104478. * @param options defines the options used to create the sphere
  104479. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  104480. * @param scene defines the hosting scene
  104481. */
  104482. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  104483. if (this._emitterNode) {
  104484. this._emitterNode.dispose();
  104485. }
  104486. this._emitterCreationOptions = {
  104487. kind: "Sphere",
  104488. options: options,
  104489. renderingGroupId: renderingGroupId
  104490. };
  104491. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  104492. emitterMesh.renderingGroupId = renderingGroupId;
  104493. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  104494. material.emissiveColor = options.color;
  104495. emitterMesh.material = material;
  104496. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104497. var system = _a[_i];
  104498. system.emitter = emitterMesh;
  104499. }
  104500. this._emitterNode = emitterMesh;
  104501. };
  104502. /**
  104503. * Starts all particle systems of the set
  104504. * @param emitter defines an optional mesh to use as emitter for the particle systems
  104505. */
  104506. ParticleSystemSet.prototype.start = function (emitter) {
  104507. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104508. var system = _a[_i];
  104509. if (emitter) {
  104510. system.emitter = emitter;
  104511. }
  104512. system.start();
  104513. }
  104514. };
  104515. /**
  104516. * Release all associated resources
  104517. */
  104518. ParticleSystemSet.prototype.dispose = function () {
  104519. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104520. var system = _a[_i];
  104521. system.dispose();
  104522. }
  104523. this.systems = [];
  104524. if (this._emitterNode) {
  104525. this._emitterNode.dispose();
  104526. this._emitterNode = null;
  104527. }
  104528. };
  104529. /**
  104530. * Serialize the set into a JSON compatible object
  104531. * @returns a JSON compatible representation of the set
  104532. */
  104533. ParticleSystemSet.prototype.serialize = function () {
  104534. var result = {};
  104535. result.systems = [];
  104536. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104537. var system = _a[_i];
  104538. result.systems.push(system.serialize());
  104539. }
  104540. if (this._emitterNode) {
  104541. result.emitter = this._emitterCreationOptions;
  104542. }
  104543. return result;
  104544. };
  104545. /**
  104546. * Parse a new ParticleSystemSet from a serialized source
  104547. * @param data defines a JSON compatible representation of the set
  104548. * @param scene defines the hosting scene
  104549. * @param gpu defines if we want GPU particles or CPU particles
  104550. * @returns a new ParticleSystemSet
  104551. */
  104552. ParticleSystemSet.Parse = function (data, scene, gpu) {
  104553. if (gpu === void 0) { gpu = false; }
  104554. var result = new ParticleSystemSet();
  104555. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  104556. scene = scene || BABYLON.Engine.LastCreatedScene;
  104557. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  104558. var system = _a[_i];
  104559. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  104560. }
  104561. if (data.emitter) {
  104562. var options = data.emitter.options;
  104563. switch (data.emitter.kind) {
  104564. case "Sphere":
  104565. result.setEmitterAsSphere({
  104566. diameter: options.diameter,
  104567. segments: options.segments,
  104568. color: BABYLON.Color3.FromArray(options.color)
  104569. }, data.emitter.renderingGroupId, scene);
  104570. break;
  104571. }
  104572. }
  104573. return result;
  104574. };
  104575. return ParticleSystemSet;
  104576. }());
  104577. BABYLON.ParticleSystemSet = ParticleSystemSet;
  104578. })(BABYLON || (BABYLON = {}));
  104579. //# sourceMappingURL=babylon.particleSystemSet.js.map
  104580. var BABYLON;
  104581. (function (BABYLON) {
  104582. /**
  104583. * This class is made for on one-liner static method to help creating particle system set.
  104584. */
  104585. var ParticleHelper = /** @class */ (function () {
  104586. function ParticleHelper() {
  104587. }
  104588. /**
  104589. * Create a default particle system that you can tweak
  104590. * @param emitter defines the emitter to use
  104591. * @param capacity defines the system capacity (default is 500 particles)
  104592. * @param scene defines the hosting scene
  104593. * @returns the new Particle system
  104594. */
  104595. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  104596. if (capacity === void 0) { capacity = 500; }
  104597. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  104598. system.emitter = emitter;
  104599. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  104600. system.createConeEmitter(0.1, Math.PI / 4);
  104601. // Particle color
  104602. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  104603. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  104604. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  104605. // Particle Size
  104606. system.minSize = 0.1;
  104607. system.maxSize = 0.1;
  104608. // Emission speed
  104609. system.minEmitPower = 2;
  104610. system.maxEmitPower = 2;
  104611. system.emitRate = 30;
  104612. return system;
  104613. };
  104614. /**
  104615. * This is the main static method (one-liner) of this helper to create different particle systems
  104616. * @param type This string represents the type to the particle system to create
  104617. * @param scene The scene where the particle system should live
  104618. * @param gpu If the system will use gpu
  104619. * @returns the ParticleSystemSet created
  104620. */
  104621. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  104622. if (gpu === void 0) { gpu = false; }
  104623. if (!scene) {
  104624. scene = BABYLON.Engine.LastCreatedScene;
  104625. ;
  104626. }
  104627. var token = {};
  104628. scene._addPendingData(token);
  104629. return new Promise(function (resolve, reject) {
  104630. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  104631. scene._removePendingData(token);
  104632. return reject("Particle system with GPU is not supported.");
  104633. }
  104634. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  104635. scene._removePendingData(token);
  104636. var newData = JSON.parse(data.toString());
  104637. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  104638. }, undefined, undefined, undefined, function (req, exception) {
  104639. scene._removePendingData(token);
  104640. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  104641. });
  104642. });
  104643. };
  104644. /**
  104645. * Static function used to export a particle system to a ParticleSystemSet variable.
  104646. * Please note that the emitter shape is not exported
  104647. * @param system defines the particle systems to export
  104648. */
  104649. ParticleHelper.ExportSet = function (systems) {
  104650. var set = new BABYLON.ParticleSystemSet();
  104651. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  104652. var system = systems_1[_i];
  104653. set.systems.push(system);
  104654. }
  104655. return set;
  104656. };
  104657. /**
  104658. * Gets or sets base Assets URL
  104659. */
  104660. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  104661. return ParticleHelper;
  104662. }());
  104663. BABYLON.ParticleHelper = ParticleHelper;
  104664. })(BABYLON || (BABYLON = {}));
  104665. //# sourceMappingURL=babylon.particleHelper.js.map
  104666. var BABYLON;
  104667. (function (BABYLON) {
  104668. /**
  104669. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  104670. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  104671. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  104672. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104673. */
  104674. var VideoDome = /** @class */ (function (_super) {
  104675. __extends(VideoDome, _super);
  104676. /**
  104677. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  104678. * @param name Element's name, child elements will append suffixes for their own names.
  104679. * @param urlsOrVideo defines the url(s) or the video element to use
  104680. * @param options An object containing optional or exposed sub element properties
  104681. */
  104682. function VideoDome(name, urlsOrVideo, options, scene) {
  104683. var _this = _super.call(this, name, scene) || this;
  104684. _this._useDirectMapping = false;
  104685. // set defaults and manage values
  104686. name = name || "videoDome";
  104687. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104688. options.clickToPlay = Boolean(options.clickToPlay);
  104689. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  104690. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  104691. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104692. if (options.useDirectMapping === undefined) {
  104693. _this._useDirectMapping = true;
  104694. }
  104695. else {
  104696. _this._useDirectMapping = options.useDirectMapping;
  104697. }
  104698. _this._setReady(false);
  104699. // create
  104700. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  104701. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104702. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  104703. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104704. texture.onLoadObservable.addOnce(function () {
  104705. _this._setReady(true);
  104706. });
  104707. // configure material
  104708. material.useEquirectangularFOV = true;
  104709. material.fovMultiplier = 1.0;
  104710. material.opacityFresnel = false;
  104711. if (_this._useDirectMapping) {
  104712. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104713. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104714. material.diffuseTexture = texture;
  104715. }
  104716. else {
  104717. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104718. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104719. material.reflectionTexture = texture;
  104720. }
  104721. // configure mesh
  104722. _this._mesh.material = material;
  104723. _this._mesh.parent = _this;
  104724. // optional configuration
  104725. if (options.clickToPlay) {
  104726. scene.onPointerUp = function () {
  104727. _this._videoTexture.video.play();
  104728. };
  104729. }
  104730. return _this;
  104731. }
  104732. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  104733. /**
  104734. * Gets the video texture being displayed on the sphere
  104735. */
  104736. get: function () {
  104737. return this._videoTexture;
  104738. },
  104739. enumerable: true,
  104740. configurable: true
  104741. });
  104742. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  104743. /**
  104744. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104745. * Also see the options.resolution property.
  104746. */
  104747. get: function () {
  104748. return this._material.fovMultiplier;
  104749. },
  104750. set: function (value) {
  104751. this._material.fovMultiplier = value;
  104752. },
  104753. enumerable: true,
  104754. configurable: true
  104755. });
  104756. /**
  104757. * Releases resources associated with this node.
  104758. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104759. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104760. */
  104761. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104762. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104763. this._videoTexture.dispose();
  104764. this._mesh.dispose();
  104765. this._material.dispose();
  104766. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104767. };
  104768. return VideoDome;
  104769. }(BABYLON.Node));
  104770. BABYLON.VideoDome = VideoDome;
  104771. })(BABYLON || (BABYLON = {}));
  104772. //# sourceMappingURL=babylon.videoDome.js.map
  104773. var BABYLON;
  104774. (function (BABYLON) {
  104775. /**
  104776. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  104777. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  104778. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  104779. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104780. */
  104781. var PhotoDome = /** @class */ (function (_super) {
  104782. __extends(PhotoDome, _super);
  104783. /**
  104784. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  104785. * @param name Element's name, child elements will append suffixes for their own names.
  104786. * @param urlsOfPhoto define the url of the photo to display
  104787. * @param options An object containing optional or exposed sub element properties
  104788. */
  104789. function PhotoDome(name, urlOfPhoto, options, scene) {
  104790. var _this = _super.call(this, name, scene) || this;
  104791. _this._useDirectMapping = false;
  104792. // set defaults and manage values
  104793. name = name || "photoDome";
  104794. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104795. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104796. if (options.useDirectMapping === undefined) {
  104797. _this._useDirectMapping = true;
  104798. }
  104799. else {
  104800. _this._useDirectMapping = options.useDirectMapping;
  104801. }
  104802. _this._setReady(false);
  104803. // create
  104804. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104805. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104806. // configure material
  104807. material.opacityFresnel = false;
  104808. material.useEquirectangularFOV = true;
  104809. material.fovMultiplier = 1.0;
  104810. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  104811. _this.photoTexture.onLoadObservable.addOnce(function () {
  104812. _this._setReady(true);
  104813. });
  104814. // configure mesh
  104815. _this._mesh.material = material;
  104816. _this._mesh.parent = _this;
  104817. return _this;
  104818. }
  104819. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  104820. /**
  104821. * Gets or sets the texture being displayed on the sphere
  104822. */
  104823. get: function () {
  104824. return this._photoTexture;
  104825. },
  104826. set: function (value) {
  104827. if (this._photoTexture === value) {
  104828. return;
  104829. }
  104830. this._photoTexture = value;
  104831. if (this._useDirectMapping) {
  104832. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104833. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104834. this._material.diffuseTexture = this._photoTexture;
  104835. }
  104836. else {
  104837. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104838. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104839. this._material.reflectionTexture = this._photoTexture;
  104840. }
  104841. },
  104842. enumerable: true,
  104843. configurable: true
  104844. });
  104845. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  104846. /**
  104847. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104848. * Also see the options.resolution property.
  104849. */
  104850. get: function () {
  104851. return this._material.fovMultiplier;
  104852. },
  104853. set: function (value) {
  104854. this._material.fovMultiplier = value;
  104855. },
  104856. enumerable: true,
  104857. configurable: true
  104858. });
  104859. /**
  104860. * Releases resources associated with this node.
  104861. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104862. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104863. */
  104864. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104865. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104866. this._photoTexture.dispose();
  104867. this._mesh.dispose();
  104868. this._material.dispose();
  104869. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104870. };
  104871. return PhotoDome;
  104872. }(BABYLON.Node));
  104873. BABYLON.PhotoDome = PhotoDome;
  104874. })(BABYLON || (BABYLON = {}));
  104875. //# sourceMappingURL=babylon.photoDome.js.map
  104876. var BABYLON;
  104877. (function (BABYLON) {
  104878. BABYLON.Engine.prototype.createQuery = function () {
  104879. return this._gl.createQuery();
  104880. };
  104881. BABYLON.Engine.prototype.deleteQuery = function (query) {
  104882. this._gl.deleteQuery(query);
  104883. return this;
  104884. };
  104885. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  104886. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  104887. };
  104888. BABYLON.Engine.prototype.getQueryResult = function (query) {
  104889. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  104890. };
  104891. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  104892. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104893. this._gl.beginQuery(glAlgorithm, query);
  104894. return this;
  104895. };
  104896. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  104897. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104898. this._gl.endQuery(glAlgorithm);
  104899. return this;
  104900. };
  104901. BABYLON.Engine.prototype._createTimeQuery = function () {
  104902. var timerQuery = this.getCaps().timerQuery;
  104903. if (timerQuery.createQueryEXT) {
  104904. return timerQuery.createQueryEXT();
  104905. }
  104906. return this.createQuery();
  104907. };
  104908. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  104909. var timerQuery = this.getCaps().timerQuery;
  104910. if (timerQuery.deleteQueryEXT) {
  104911. timerQuery.deleteQueryEXT(query);
  104912. return;
  104913. }
  104914. this.deleteQuery(query);
  104915. };
  104916. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  104917. var timerQuery = this.getCaps().timerQuery;
  104918. if (timerQuery.getQueryObjectEXT) {
  104919. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  104920. }
  104921. return this.getQueryResult(query);
  104922. };
  104923. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  104924. var timerQuery = this.getCaps().timerQuery;
  104925. if (timerQuery.getQueryObjectEXT) {
  104926. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  104927. }
  104928. return this.isQueryResultAvailable(query);
  104929. };
  104930. BABYLON.Engine.prototype.startTimeQuery = function () {
  104931. var caps = this.getCaps();
  104932. var timerQuery = caps.timerQuery;
  104933. if (!timerQuery) {
  104934. return null;
  104935. }
  104936. var token = new BABYLON._TimeToken();
  104937. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104938. if (caps.canUseTimestampForTimerQuery) {
  104939. token._startTimeQuery = this._createTimeQuery();
  104940. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  104941. }
  104942. else {
  104943. if (this._currentNonTimestampToken) {
  104944. return this._currentNonTimestampToken;
  104945. }
  104946. token._timeElapsedQuery = this._createTimeQuery();
  104947. if (timerQuery.beginQueryEXT) {
  104948. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104949. }
  104950. else {
  104951. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104952. }
  104953. this._currentNonTimestampToken = token;
  104954. }
  104955. return token;
  104956. };
  104957. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  104958. var caps = this.getCaps();
  104959. var timerQuery = caps.timerQuery;
  104960. if (!timerQuery || !token) {
  104961. return -1;
  104962. }
  104963. if (caps.canUseTimestampForTimerQuery) {
  104964. if (!token._startTimeQuery) {
  104965. return -1;
  104966. }
  104967. if (!token._endTimeQuery) {
  104968. token._endTimeQuery = this._createTimeQuery();
  104969. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  104970. }
  104971. }
  104972. else if (!token._timeElapsedQueryEnded) {
  104973. if (!token._timeElapsedQuery) {
  104974. return -1;
  104975. }
  104976. if (timerQuery.endQueryEXT) {
  104977. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  104978. }
  104979. else {
  104980. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  104981. }
  104982. token._timeElapsedQueryEnded = true;
  104983. }
  104984. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104985. var available = false;
  104986. if (token._endTimeQuery) {
  104987. available = this._getTimeQueryAvailability(token._endTimeQuery);
  104988. }
  104989. else if (token._timeElapsedQuery) {
  104990. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  104991. }
  104992. if (available && !disjoint) {
  104993. var result = 0;
  104994. if (caps.canUseTimestampForTimerQuery) {
  104995. if (!token._startTimeQuery || !token._endTimeQuery) {
  104996. return -1;
  104997. }
  104998. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  104999. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  105000. result = timeEnd - timeStart;
  105001. this._deleteTimeQuery(token._startTimeQuery);
  105002. this._deleteTimeQuery(token._endTimeQuery);
  105003. token._startTimeQuery = null;
  105004. token._endTimeQuery = null;
  105005. }
  105006. else {
  105007. if (!token._timeElapsedQuery) {
  105008. return -1;
  105009. }
  105010. result = this._getTimeQueryResult(token._timeElapsedQuery);
  105011. this._deleteTimeQuery(token._timeElapsedQuery);
  105012. token._timeElapsedQuery = null;
  105013. token._timeElapsedQueryEnded = false;
  105014. this._currentNonTimestampToken = null;
  105015. }
  105016. return result;
  105017. }
  105018. return -1;
  105019. };
  105020. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  105021. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  105022. };
  105023. // We also need to update AbstractMesh as there is a portion of the code there
  105024. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  105025. var engine = this.getEngine();
  105026. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  105027. this._isOccluded = false;
  105028. return;
  105029. }
  105030. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  105031. this._isOccluded = false;
  105032. return;
  105033. }
  105034. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  105035. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  105036. if (isOcclusionQueryAvailable) {
  105037. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  105038. this._isOcclusionQueryInProgress = false;
  105039. this._occlusionInternalRetryCounter = 0;
  105040. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  105041. }
  105042. else {
  105043. this._occlusionInternalRetryCounter++;
  105044. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  105045. this._isOcclusionQueryInProgress = false;
  105046. this._occlusionInternalRetryCounter = 0;
  105047. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  105048. // if strict continue the last state of the object.
  105049. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  105050. }
  105051. else {
  105052. return;
  105053. }
  105054. }
  105055. }
  105056. var scene = this.getScene();
  105057. if (scene.getBoundingBoxRenderer) {
  105058. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  105059. if (!this._occlusionQuery) {
  105060. this._occlusionQuery = engine.createQuery();
  105061. }
  105062. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  105063. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  105064. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  105065. this._isOcclusionQueryInProgress = true;
  105066. }
  105067. };
  105068. })(BABYLON || (BABYLON = {}));
  105069. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  105070. var BABYLON;
  105071. (function (BABYLON) {
  105072. /**
  105073. * Class used to generate noise procedural textures
  105074. */
  105075. var NoiseProceduralTexture = /** @class */ (function (_super) {
  105076. __extends(NoiseProceduralTexture, _super);
  105077. /**
  105078. * Creates a new NoiseProceduralTexture
  105079. * @param name defines the name fo the texture
  105080. * @param size defines the size of the texture (default is 256)
  105081. * @param scene defines the hosting scene
  105082. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  105083. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  105084. */
  105085. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  105086. if (size === void 0) { size = 256; }
  105087. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  105088. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  105089. _this._time = 0;
  105090. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  105091. _this.brightness = 0.2;
  105092. /** Defines the number of octaves to process */
  105093. _this.octaves = 3;
  105094. /** Defines the level of persistence (0.8 by default) */
  105095. _this.persistence = 0.8;
  105096. /** Gets or sets animation speed factor (default is 1) */
  105097. _this.animationSpeedFactor = 1;
  105098. _this._updateShaderUniforms();
  105099. return _this;
  105100. }
  105101. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  105102. var scene = this.getScene();
  105103. if (!scene) {
  105104. return;
  105105. }
  105106. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  105107. this.setFloat("brightness", this.brightness);
  105108. this.setInt("octaves", this.octaves);
  105109. this.setFloat("persistence", this.persistence);
  105110. this.setFloat("timeScale", this._time);
  105111. };
  105112. /** Generate the current state of the procedural texture */
  105113. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  105114. this._updateShaderUniforms();
  105115. _super.prototype.render.call(this, useCameraPostProcess);
  105116. };
  105117. /**
  105118. * Serializes this noise procedural texture
  105119. * @returns a serialized noise procedural texture object
  105120. */
  105121. NoiseProceduralTexture.prototype.serialize = function () {
  105122. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  105123. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  105124. return serializationObject;
  105125. };
  105126. /**
  105127. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  105128. * @param parsedTexture defines parsed texture data
  105129. * @param scene defines the current scene
  105130. * @param rootUrl defines the root URL containing noise procedural texture information
  105131. * @returns a parsed NoiseProceduralTexture
  105132. */
  105133. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  105134. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  105135. return texture;
  105136. };
  105137. return NoiseProceduralTexture;
  105138. }(BABYLON.ProceduralTexture));
  105139. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  105140. })(BABYLON || (BABYLON = {}));
  105141. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  105142. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\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 mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<octaves; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  105143. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(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;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(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=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(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#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\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;\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};"};